New to React: I am trying to update a “story” that is in an array stored in state.
My function saves the changes to an API (which works) but fails to update the state array. I receive the error
state.stories.map is not a function
TypeError: state.stories.map is not a function
It is my understanding that I should MAP the array and update the item that needs to be updated… But the function doesn’t see my state.stories.map as a function.
I am also not sure if I can access action.payload variables the way I have. (If not, I haven’t discovered that error, as my code hasn’t gotten that far…) The Payload is this:
My Reducers is setup like this:
const initialState = {
stories: [],
isLoading: false,
currentStory: {},
error: "",
};
function reducer(state, action) {
switch (action.type) {
case "loading":
return { ...state, isLoading: true, error: "" };
case "stories/loaded":
return { ...state, isLoading: false, stories: action.payload, error: "" };
case "story/loaded":
return {
...state,
isLoading: false,
currentStory: action.payload,
error: "",
};
case "story/created":
return {
...state,
isLoading: false,
//stories: [...state.stories, action.payload],
currentStory: action.payload,
error: "",
};
case "story/updated":
return {
...state,
isLoading: false,
stories: [
state.stories.map((story) =>
story.StoryID === action.payload.StoryID
? {
...state.stories,
StartDate: action.payload.StartDate,
EndDate: action.payload.EndDate,
StoryTitle: action.payload.StoryTitle,
StoryText: action.payload.StoryText,
}
: story
),
],
currentStory: action.payload,
};
... etc
Function:
function StoriesProvider({ children }) {
const { user } = useAuth();
const [{ stories, isLoading, currentStory, error }, dispatch] = useReducer(
reducer,
initialState
);
async function updateStory(theStory, StoryID) {
dispatch({ type: "loading" });
try {
const res = await fetch(
`${BASE_URL}/stories/${StoryID}/${user.UserInfo[0].CustUUID}`,
{
method: "PUT",
body: JSON.stringify(theStory),
headers: { "Content-Type": "application/json" },
}
);
dispatch({ type: "story/updated", payload: theStory });
} catch {
dispatch({
type: "rejected",
payload: "There was an error updating story data.",
});
}
}