1

Hi I am learning hooks concept by developing a small application. I am using redux slices. I am not following traditional way to create state like([state, setState]), instead I am creating states under one variable called intialState. I am trying to perform CRUD operation in application by hitting an external API. I am trying to delete the value from the list by button click.Under intialState variable am having a state called courses:[], where I used to store the data from the end point. When I am performing Delete operation I want to setState for this courses. I have tried to set the state but I ended up with error. Can any one help me out with how to set state in below method. Thanks in advance. Below is my code.

const initialState = {
  isLoading: false,
  error: false,
  courses: [],
};

//------------------Delete Course

export function deleteCourse(index, id) {
  console.log('I am coming');
  axios.delete(`edu/course/${id}`).then(res => {
    const newCourseList = [...initialState.courses];
    console.log('NEW COURSE LIST', newCourseList);
    newCourseList.splice(index, 1);
    setinitialState({ courses: newCourseList }); // If I am doing like this I am getting an 
                                                    error
  });
}
Still_Learning
  • 209
  • 3
  • 14

2 Answers2

0

just be careful about setting argument in react. You have a variable named initialState and you don't have some variable like setinitialState right but that's the point that react provide us to change our variables with set in this way. But there is a big point to creaful is that you should use that like setVariableValues so

 setinitialState({ courses: newCourseList }); 

change to

setInitialState({ courses: newCourseList }); 

hope works ;)

0

I am going to guess the issue/error is related to dropping the rest of your state when you set the courses state.

setinitialState({ courses: newCourseList }); // <-- fully replaces state

Recall that in functional components state updates are not shallowly merged.

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

const [state, setState] = useState({});
setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

Use a functional state update to update from the previous state, shallow copy the previous state and then use a filter function to filter the courses array by the matching index.

export function deleteCourse(index, id) {
  axios.delete(`edu/course/${id}`).then(res => {
    setinitialState(prevState => ({
      ...prevState,
      courses: prevState.courses.filter((_, i) => i !== index),
    }));
  });
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181