Home > database >  Implementing Redux functionality using Context and Reducers in React not working Properly
Implementing Redux functionality using Context and Reducers in React not working Properly

Time:10-18

So i am trying to implement the functionality of redux using only react hooks as shown in the following links enter image description here

After clicking 3 or 4 times enter image description here

enter image description here

Here is my folder structure just in case you think i am importing wrong stuff

enter image description here

Button component

import './Button.css';
import React, {useEffect, useContext} from 'react';
import {Context} from '../../store/Store.js';

const Button = ( props ) => {

const [state, dispatch] = useContext(Context);

const incrementAction = () => {
    dispatch({
        type:'DO_ACTION',
        payload: 1
    })
    console.log(state.number);
  };

return (
    <div>
        <button onClick={() => incrementAction()}>Display Number!!!!</button>
        <div>{state.number}</div>
    </div>
    )
};

export default Button

here is my reducer

const Reducer = (state, action) => {
switch (action.type) {
    case 'DO_ACTION':
        return state   action.payload
    }
};

export default Reducer;

Here is my global store and HOC

import React, {createContext, useReducer} from "react";
import Reducer from './Reducer';


const initialState = {
    number: 5
};

const Store = ({children}) => {
    const [state, dispatch] = useReducer(Reducer, initialState);
    
    return (
        <Context.Provider value={[state, dispatch]}>
            {children}
        </Context.Provider>
    )
};

export const Context = createContext(initialState);
export default Store;

And here is my main App component that is wrapped with store to have it accessible throughout my app

import Store from './store/Store.js';
import Button from './components/Button/Button.js';

const App = () => {

    return (
        <div>
          <Store>
            <Button />
            <OtherComponents /> //a bunch of other components go here like title, paging etc
          </Store>
        </div>
    );
}

export default App;

CodePudding user response:

You need to be returning the whole (cloned) state object from your reducer function, not just the property you want to update. You should also make sure you have a default case:

const Reducer = (state, action) => {
    switch (action.type) {
        case 'DO_ACTION':
            return {
                number: state.number   action.payload
            }
        default:
            return state;
    }
};

export default Reducer;

If you have more than one property in your state object you must remember to clone all of the other properties into it as well (e.g. {...state, number: state.number action.payload}).

  • Related