I Note have a state in redux like this:
const initialState = {
data: [],
loading: false,
success: false,
error: null,
};
I have created CRUD API in the node backend.
I have two components in react
the first component is to add a new note to the database
which have a normal textarea input.
function in noteSlice.js is:
export const addNote = createAsyncThunk("addNote", async (data) => {
try {
await axiosInstance.post("/api/note/add", data);
return "Note has been added";
} catch (err) {
console.log(err);
return err.message;
}
});
And in slice:
extraReducers: (builder) => {
builder.addCase(addNote.pending, (state) => {
state.loading = true;
state.success = false;
state.error = null;
});
builder.addCase(addNote.fulfilled, (state) => {
state.loading = false;
state.success = true;
state.error = null;
});
builder.addCase(addNote.rejected, (state, { payload }) => {
state.loading = false;
state.success = false;
state.error = payload;
});
.../other cases
In Second Component I have displayed all notes by date sorting:
Which look like this:
const Note = ({ cardId }) => {
const { loading, data, error, success } = useSelector((state) => state.note);
const dispatch = useDispatch();
function deleteNoteFn(id) {
dispatch(deleteNote(id));
}
useEffect(() => {
dispatch(getNotesByCardId(cardId));
}, [cardId, success]);
// returning html
Getting Note Function in slice
// GET DEAL
builder.addCase(getNotesByCardId.pending, (state) => {
state.loading = true;
state.success = false;
state.error = null;
});
builder.addCase(getNotesByCardId.fulfilled, (state, { payload }) => {
state.loading = false;
state.success = true;
state.data = payload;
state.error = null;
});
builder.addCase(getNotesByCardId.rejected, (state, { payload }) => {
state.loading = false;
state.success = false;
state.error = payload;
});
when ever i add a new note. I want to reload all notes by success state which is shown in useeffect.
but the getNotesByCardId is also changing success state so useEffect creates the loop for this is code.
please help me thank you.
I have tried removing the success state changing from getNotesByCardId.fullfilled but i want this state to be there.
thank you in advance for your adivce
You don't need 'success' in the dependency list of useEffect. Removing it should fix the issue.