Redux State does not change the value

Viewed 25

Good morning people! I have a question, I can't change my "userReducer.js" states and I can't type anything in the "name" value input. What is causing this error? I created a state named test with the type number in place of the input "name" and the value was changed in the component "App.js", however the state in the "userReducer" was not changed.

userReducer.js:

import { createSlice } from '@reduxjs/toolkit';

const slice = createSlice({
    name: 'user',
    initialState: {
        name: 'bonieky',
        age: 90,
    },
    
    reducers: {
        setName: (state, action) => {
            state.name = action.payload
        },
        setAge: (state, action) => {
            state.age = action.payload;
        },
    }
});

export const { setName, setAge } = slice.actions;
export default slice.reducer;

store.js:

import {configureStore} from '@reduxjs/toolkit';

import userReducer from './reducers/userReducer';

import themeReducer from './reducers/themeReducer';

export const store = configureStore({
    reducer: {
        user: userReducer,
        theme: themeReducer,
    }
});

App.js:

import {useDispatch} from 'react-redux';
import {setName, setAge} from './redux/reducers/userReducer';
import { useSelector } from 'react-redux';

function App() {
  const dispatch = useDispatch();

  const user = useSelector((state)=> state.user);

  const handleNameInput = (e) => {
    dispatch(setName(e.targe.value));
  }

  const handleAgeInput = (e) => {
    dispatch(setAge(e.target.value));
  }
 

  return (
    <div>
      Meu name is {user.name} and I am  {user.age} years old. <br/> 

      <hr />
      <input type="text" value={user.name} onChange={handleNameInput} />
      <input type="text" value={user.age} onChange={handleAgeInput} />
      
    </div>
  );
}

export default App;

index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import { Provider } from 'react-redux';
import { store } from './redux/store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

reportWebVitals();

repository link

1 Answers

There's a typo in the following function. It should be e.target.value.

const handleNameInput = (e) => {
    dispatch(setName(e.targe.value));
}

To debug an unexpected behaviour, I would recommend you to include "looking up in the browser console" in your debugging regime.

For instance, you would have seen the following error in the console. The following message tells us that something is wrong in handleNameInput and the program is having trouble while reading .value.

enter image description here

Related