0

I'm trying to do some work using the useReducer hook and react-router-dom. I have 2 pages; 1) Home 2) Details. Using the react-router-dom to navigate between 2 components. The details are added to the details page. In the submit action of the Details page the despatch() is called to save the state.

// In Details.js component
const [details, setDetails] = useState({
    name: '',
    age: ''
});
const save_book = (e) => {
    e.preventDefault();
    const modified_details = {...details, id: uuidv4()};
    dispatch({ type: 'SAVE', payload: modified_details});
}

The reducer.js file

export const default_state = {
    details: []
}

// Reducer
export const reducer = (state, action) => {

    if(action.type === 'SAVE'){
        const modified_details = [...state.details, action.payload];
        console.log(state);
        return {...state, details: modified_details};
    }

    throw new Error ('HANDLED_ERROR: matching action type found!');
}

The details are saved in state successfully. But when I try to navigate to the Home component the state is set to initial.

//In Home.js component
const Home = () => {
    const [state, dispatch] = useReducer(reducer, default_state);
    // This is a new state variable???

    // This is empty. 
    // {
    //   "details": []
    // }
    return(<> <pre>{JSON.stringify(state, undefined, 2)}</pre> </>);
}

What I'm doing wrong?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
simpywatch
  • 43
  • 5
  • Can you share how you configured your redux? Because, if you're using useReducer the state will be exclusive to the component, except for cases where you're passing it down as props to a child component. – Mbiplang Ardel Jun 11 '21 at 16:50
  • 1
    The state in a `useReducer` hook is local to the component. When the component unmounts it goes away, when the component mounts, it's re-instantiated. Seems you want, or need, to [Lift State Up](https://reactjs.org/docs/lifting-state-up.html) or some other method of persisting the state such that when you are navigating around your app it persists. – Drew Reese Jun 11 '21 at 17:20
  • @JothamArdel thanks for the information regarding 'useReducer'. – simpywatch Jun 14 '21 at 04:33
  • 1
    @DrewReese Thanks for the edits and information regarding `useReducer`. – simpywatch Jun 14 '21 at 04:33

0 Answers0