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?