Problem with React and Redux

Asked

Viewed 338 times

3

Hi... I’m studying React and now Redux. I’m trying to make a simple example: Where I have an input and button, I want to enter a value in the input and when clicking the button take the value and add 1.

I managed to make:

  • Click on the button to pick up the value and display elsewhere.
  • Click on the button to take the initial value and add 1.

But I want to enter the value and click add 1;

I have the following code:

type js.

export const CLICK_BOTAO = 'CLICK_BOTAO',
             DIGITAR_VALOR = 'DIGITAR_VALOR';

actions.js

import {
     CLICK_BOTAO,
     DIGITAR_VALOR
 } from './types';

const _valor = (valor) => {
    let s =0;
    let t =parseFloat( s + valor)
    return t;
};

export const clickBotao = value => ({
    type: CLICK_BOTAO,
    novoValor: _valor(value)
});

export const digitarValor = ev => ({
    type: DIGITAR_VALOR,
    novoValor: ev.target.value
});

index.js reducers

import {combineReducers} from 'redux';
import clientesReducer from './clientesReducer';

const rootReducer = combineReducers({
    click: clientesReducer
})

export default rootReducer;

clientesReducers.js

import {
    CLICK_BOTAO,
    DIGITAR_VALOR
} from '../actions/types';

const inicial = {
    novoValor: 0
}

export default (state =  inicial, action) => {
    switch(action.type) {
        case CLICK_BOTAO:
            return {
                ...state,
                novoValor: action.novoValor
            };

        case DIGITAR_VALOR:
            return {
                ...state,
                novoValor: action.novoValor
            };
        default:
            return state;
    }
};

Application.js

import React, { Component } from "react";
import { connect } from "react-redux";
import * as actions from "../actions/index";

class Aplicacao extends Component {
  constructor(props) {
    super(props);

    this.state = {
      inputValue: 0
    };
  }

  inputChange = event => {
    this.setState({
      inputValue: this.props.digitarValor(this.props.novoValor) 
    }, ()=>{
      console.log(this.state.inputValue);
    });
  };

  soma = () => {
    this.setState({
      inputValue: this.state.inputValue + 1
    }, () => {
          this.props.clickBotao(this.state.inputValue)
          console.log(`--- ${this.state.inputValue}`);
    }
    );

  }

  render() {
    const { novoValor, digitarValor: onChange } = this.props;

    return (
      <div className="App" style={{ padding: "20px" }}>
        <input
          onChange={onChange}
          type="text"
          value={novoValor}
        />
        <button onClick={this.soma}>
          Clique aqui
        </button>
        <h1>{novoValor}</h1>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  novoValor: state.click.novoValor
});

export default connect(
  mapStateToProps,
  actions
)(Aplicacao);

What should change to get the result I want?

  • You want to add the value 1 to the click or add the value of what was typed?

  • I’m not sure, but try passing the direct value instead of Ev.target.value to your action. Actually if you are going to analyze, if you want to add only the entered value, you don’t even need the DIGITAR_VALOR action. Just let your button click action take the value of Event.target.value inside the same component.

  • Just clicking I managed to do and already this adding... only it always starts from 0 ai I click 1 - 2 -3 .... I want to enter the value in the input and add example: Type 10 and click there it takes the 10 + 1 = 11 and ai 12 - 13 - 14.

2 answers

4


Alex, okay? Dude, I made the code and attached it to Github to make your life easier. This is the link (https://github.com/victorhermes/SomarNumerosReact)

A tip that I give you when developing, is to paste the files related to Redux (actions, reducers, sagas and configuration files) all inside a store folder, thus becoming more organized. Going back to your code, the only thing I did was to export the function, call the switch next to the SOMAR case, copy all the state with ES6 spread (that would be the ...state), call the initial state (that would be the number inside the INITIAL_STATE) and put the new value that comes by the action (in this case, action.payload.number), finally put + 1 to do the sum. An important detail is to use parseint() to transform the string number to integer.

The end result looks like this: Resultado final

And adding the javascript increment, we get the result below. That in addition to just add, to each click, makes an increment of more 1.

inserir a descrição da imagem aqui

I hope the code solves your problem :)

  • 1

    Just by complementing Victor, this question of putting everything related to Redux (actions, reducers and types) in a folder is a concept called Duckpattern. #Vivabootcamp

  • 1

    Dude worked.... let me tell you... where do you live? Because I’m going to camp outside your house, to see if I can learn this booze... I’m taking a beating... rsrs. Now, I like the tip to put the files inside the same folder as you did. I am following some tutorials and the staff put separate so I did the same. Now a question you did not use the file type.js? And thank you so much for working to clear up my doubt.

  • Kkkkk. Dude, how cool that worked. I’m happy. So you can use it with the type too. This concept I used is called Duck Pattern (As Daniel Obara commented) and is nothing more than putting actions, types and reducers in a single file. This is for larger applications, because when we make applications that are large, it has several types, actions and reducers and there are several files, making it difficult to maintain and legible. To minimize the problem, we put all this together and turn this Duck Pattern.

  • I recommend watching the Rocketseat videos... which in my opinion are national references of JS content. See link below: https://www.youtube.com/watch?v=q-If9n-tUyA

  • Hi Daniel I’m already enrolled in this channel... already watching some videos cleared me a lot. I’m thinking of taking a course at Udemy. Know? You know another good online?

2

This is Alex, all right? Dude, this kind of change is best done inside the Reset. It would look something like this:

Actions

import {
     CLICK_BOTAO,
     DIGITAR_VALOR
 } from './types';

// Alterei sua Action aqui e retirei a função de somar valor
export const clickBotao = value => ({
    type: CLICK_BOTAO,
    payload: { value }
});

export const digitarValor = ev => ({
    type: DIGITAR_VALOR,
    novoValor: ev.target.value
});

clientesReducers.js

import {
    CLICK_BOTAO,
    DIGITAR_VALOR
} from '../actions/types';

const inicial = {
    novoValor: 0
}

export default (state =  inicial, action) => {
    switch(action.type) {
        case CLICK_BOTAO:
            return {
                ...state,
                // Vamos transformar o value em INT
                novoValor: state.novoValor + parseInt(action.payload.value, 0)
            };

        case DIGITAR_VALOR:
            return {
                ...state,
                novoValor: action.novoValor
            };
        default:
            return state;
    }
};

See if it works and give it a call.

  • Hello... dude didn’t work. Now this getting so type in the input field 10 and when I click returns 010 and each click adds 10 like this: 010101010.... that is to say this concatenating and not adding

  • and try to convert before adding?

  • Daniel... I don’t understand

  • Convert the value to float newValue: state.newValor + action.payload.value. Just an assumption...

  • I’ll update the answer there. It’s going string instead of Int.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.