1
votes

I want to add a data to the restfull api by action. But I get this error.

export const GlobalContext = createContext();
const GlobalProvider = ({ children }) => {
const [userData, setUserData] = useState([]);
const [meetings, setMeetings] = useState([]);
useEffect(() => {
    fetch('http://localhost:4000/users')
        .then(res => res.json())
        .then(data => {
            setUserData(data);
            dispatch({
                type: 'CREATE_MEETING',
                paylaod: data
            })
        });
    fetch('http://localhost:4000/meeting')
        .then(res => res.json())
        .then(data => setMeetings(data));
}, []);
const [state, dispatch] = useReducer(AppReducer, meetings);
//Actions
const updateProfile = (id) => {
    dispatch({
        type: 'UPDATE_PROFILE',
        payload: id
    })
};
const createMeeting = (meeting) => {
    dispatch({
        type: 'CREATE_MEETING',
        paylaod: meeting
    })
};
return (
    <GlobalContext.Provider value={{
        meeting: meetings, userData, createMeeting
    }}>
        <MuiPickersUtilsProvider utils={DateFnsUtils}>
            {children}
        </MuiPickersUtilsProvider>
    </GlobalContext.Provider>
)

} export default GlobalProvider

enter image description here reducer const reducer = (state, action) => { switch (action.type) { case 'CREATE_MEETING': return { meeting: [action.payload, ...state.meetings] }

    default:
        return state;
}

} export default reducer;

How can I add data to the api with fetch?

 case 'CREATE_MEETING':
        console.log(state)
        return [...state,
        fetch('http://localhost:4000/meeting', {
            method: 'POST',
            headers: { "Content-type": "Application/json" },
            body: JSON.stringify(state)
        })
        ]  

could you help me please?

1
What do you get when you console.log(state.meetings) in your reducer before return statement?Luka
Are you sure, to correctly call the dispatch in the right order? Aren't you suppose to call the dispatch on the response to http://localhost:4000/meeting fetch?Martin Valentino
I receive an undefinedamirhossein
There's a typo in the createMeeting action. paylaod should be payloadj-petty

1 Answers

2
votes

As explained in Spreading undefined in array vs object you get a TypeError when trying to spread undefined.

Either wrap your setMettings in a conditional:

data => {
    if (data) {
        setMeetings(data)
    }
}

Or provide a default for state.mettings in your reducer:

const reducer = (state, action) => { 
    switch (action.type) {
        case 'CREATE_MEETING':
            return { meeting: [action.payload, ...(state.meetings || [])] }
    }
}