amirhossein
amirhossein

Reputation: 371

how to add data to the rest api with context api in react?

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?

Upvotes: 1

Views: 348

Answers (1)

j-petty
j-petty

Reputation: 3026

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 || [])] }
    }
}

Upvotes: 2

Related Questions