Search code examples
reactjsstatereact-lifecycleunmount

How to clear the state so that the previous state doesn't render in the current component?


In my recipe app, when a user clicks on a particular recipe, it renders all the details of clicked recipe in a component recipeById. When I navigate back to landing page, and select another recipe, in my UI; it first renders the data of the previously selected recipe and re-renders the data of the newly selected recipe, what should I do to prevent it???

recipeReducer.js

import { GET_RECIPES, GET_RECIPE_BY_ID} from "../actions/types.js"; 
const initialState = { 
      recipes: [],
      recipe:{}
};

export default function (state = initialState, action) { 
    switch(action.type) {
        case GET_RECIPES:
             return {
                     ...state,  
                     recipes:action.payload
                    }; 
        case GET_RECIPE_BY_ID:
             return {
                     ...state,  
                     recipe:action.payload
                    }; 
        default:
             return state; 
}

recipeActions.js

import { GET_RECIPES, GET_RECIPE_BY_ID} from "./types.js"; 
import axios from 'axios'; 

export const getRecipes = () =>async dispatch => { ... }
export const getRecipeById = (id) =>async dispatch => { 
     const res = await axios.get(`/api/recipe/${id})
     dispatch({
           type:GET_RECIPE_BY_ID,
           payload: res.data
     }); 
}

recipeById.js

import React, {component} from 'react'; 
import {connect} from 'react-redux'; 
import {getRecipeById} from '../../actions/recipeActions.js'; 
import RecipeCard from './RecipeCard'; 

class RecipeById extends Component {
    constructor(props) {
       super(props); 
     } 

  componentDidMount = async() => {
    this.props.getRecipeById(this.props.match.params.id);    
  }

  render() {
     return(
         <RecipeCard 
           title={recipe.title}
           description={recipe.description}
           image= {recipe.image}
          />
     )
  }
}
const mapStateToProps = state => ({
       recipes: state.recipe.recipes,
       recipe: state.recipe.recipe
}); 
export default connect(mapStateToProps, {getRecipeById})(RecipeById);  



Solution

  • You need to clear your data before unmount that component.

    To do that, create another action (for eg: clearData)

    Then, in your RecipeDetail component, add a componentWillUnmount() which has that declared action:

    componentWillUnmount() { 
      this.props.clearData();
    }
    

    In your reducer:

    case CLEAR_DATA: 
      return {
        ...state,
        recipe: {}
      }
    

    So data in your detail page will be cleared before you navigate back to your list page.