0

I am making a todo/shopping list in ReactJS. Besides being able to add items manually to the list by input, the user should also be able to add items programmatically.

I am using createContext() and useReducer for managing the state().

When I add items programmatically by providing an array through the props and listen for changes in useEffect, the useEffect and dispatch fires twice despite that I only changed the props once.

However this is NOT happening when I provide the array of items through props the first time.

Consequently, after the first time, when dispatch fires twice the list get duplicates (also duplicate keys).

Is it happening due to some re-rendering process that I am not aware of? Any help is much appreciated as I am really stuck on this one.

Here is the code:

Context provider component containing the useEffect that triggers the dispatch method from useReducer when the props change:

import React, { createContext, useEffect, useReducer } from 'react';
import todosReducer from '../reducers/todos.reducer';
import { ADD_INGREDIENT_ARRAY } from '../constants/actions';

const defaultItems = [
  { id: '0', task: 'Item1', completed: false },
  { id: '1', task: 'Item2', completed: false },
  { id: '2', task: 'Item3', completed: false }
];

export const TodosContext = createContext();
export const DispatchContext = createContext();

export function TodosProvider(props) {
  const [todos, dispatch] = useReducer(todosReducer, defaultItems)

  useEffect(() => {
    if (props.ingredientArray.length) {
      dispatch({ type: ADD_INGREDIENT_ARRAY, task: props.ingredientArray });
    }
  }, [props.ingredientArray])

  return (
    <TodosContext.Provider value={todos}>
      <DispatchContext.Provider value={dispatch}>
        {props.children}
      </DispatchContext.Provider>
    </TodosContext.Provider>
  );
}

My reducer function (ADD_INGREDIENT_ARRAY is the one that gets called from above code snippet) :

import uuidv4 from "uuid/dist/v4";
import { useReducer } from "react";
import {
  ADD_TODO,
  REMOVE_TODO,
  TOGGLE_TODO,
  EDIT_TODO,
  ADD_INGREDIENT_ARRAY
} from '../constants/actions';

const reducer = (state, action) => {
  switch (action.type) {
    case ADD_TODO:
      return [{ id: uuidv4(), task: action.task, completed: false }, ...state];
    case REMOVE_TODO:
      return state.filter(todo => todo.id !== action.id);
    case TOGGLE_TODO:
      return state.map(todo =>
        todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
      );
    case EDIT_TODO:
      return state.map(todo =>
        todo.id === action.id ? { ...todo, task: action.task } : todo
      );
    case ADD_INGREDIENT_ARRAY: 
        console.log('THE REDUCER WAS CALLED')
        return [...action.task.map(ingr => ({ id: uuidv4(), task: ingr.name, completed: false }) ), ...state]
    default:
      return state;
  }
};

export default reducer;

The list component that renders each item and uses the context from above code snippet:

import React, { useContext, useEffect, useState } from 'react';
import { TodosContext, DispatchContext } from '../contexts/todos.context';
import Todo from './Todo';

function TodoList() {
  const todos = useContext(TodosContext);

  return (
    <ul style={{ paddingLeft: 10, width: "95%" }}>
      {todos.map(todo => (
        <Todo key={Math.random()} {...todo} />
      ))}
    </ul>
  );
}

export default TodoList;

And the app component containing the list which is wrapped in the context provider that passes the props:

import React, { useEffect, useReducer } from 'react';
import { TodosProvider } from '../contexts/todos.context';
import TodoForm from './TodoForm';
import TodoList from './TodoList';

function TodoApp({ ingredientArray }) {
  return (
    <TodosProvider ingredientArray={ingredientArray}>
      <TodoForm/>
      <TodoList/>
    </TodosProvider>
  );
}

export default TodoApp;

And the top level component that passes the props as well:

import React, { useEffect, useContext } from 'react';
import TodoApp from './TodoApp';
import useStyles from '../styles/AppStyles';
import Paper from '@material-ui/core/Paper';

function App({ ingredientArray }) {
  const classes = useStyles();  

  return (
    <Paper className={classes.paper} elevation={3}>
      <div className={classes.App}>
        <header className={classes.header}>
          <h1>
            Shoppinglist
        </h1>
        </header>
        <TodoApp ingredientArray={ingredientArray} />
      </div>
    </Paper>
  );
}

export default App;

The parent component where ingredientArray is made. It takes the last recipe in the state.recipes array and passes it as props to the shoppingList:

...
  const handleSetNewRecipe = (recipe) => {
    recipe.date = state.date;
    setState({ ...state, recipes: [...state.recipes, recipe] })
  }
...

 {recipesOpen ? <RecipeDialog
    visible={recipesOpen}
    setVisible={setRecipesOpen}
    chosenRecipe={handleSetNewRecipe}
  /> : null}

...

 <Grid item className={classes.textAreaGrid}>
     <ShoppingList ingredientArray={state.recipes.length ? state.recipes.reverse()[0].ingredients : []}/>
 </Grid>

....

What am I doing wrong?

Ash 8851
  • 3
  • 4
  • Can you show where `ingredientArray` is being declared originally? – lawrence-witt Nov 17 '20 at 14:08
  • Yes, it is originally derived from the state of the parent component: – Ash 8851 Nov 17 '20 at 14:51
  • Should have updated the question now with a snippet from the parent component – Ash 8851 Nov 17 '20 at 15:00
  • The Array method `reverse` is mutating - React state relies on immutability so calling this method on it directly is likely to cause peculiarities, although I can't see exactly where the issue would be. Could you try this instead just to make sure: `state.recipies[state.recipies.length-1].ingredients`. – lawrence-witt Nov 17 '20 at 15:54
  • You are right! This worked for me, thank you very much. If you post this as an answer I will accept it ;)) – Ash 8851 Nov 17 '20 at 19:43

1 Answers1

0

Glad we got this sorted. As per the comments on the main post, mutating React state directly instead of updating it via a setter function can cause the actual value of the state to become out of sync with dependent components and effects further down the tree.

I still can't completely reason why it would be causing your specific issue in this case, but regardless, removing the mutative call to reverse and replacing it with this simple index calculation appears to have solved the issue:

state.recipies[state.recipies.length-1].ingredients

lawrence-witt
  • 8,094
  • 3
  • 13
  • 32