score:4

Accepted answer
const SetDataContextProvider = ({ children }) => {
    const [state, setState] = useState({
        posts: [],
        timelinePosts: [],
        createNewPost: async (collection, payload) => {
            const doc = await createDoc(collection, payload)
            payload.id = doc?.doc?.id;
            updateStatePosts(payload);
            return doc;
        },
        getPostsByUserId: async (userId) => {
            const dataReceived = await getWhere('/posts', userId, 'userId')
            setState(prevState => ({
                ...prevState, // <-- preserve any previous state
                posts: dataReceived
            }))
        }
    });

    const updateStatePosts = (payload) => {
        setState(prevState => ({ // <-- previous state to this update
            ...prevState,
            posts: [payload, ...prevState.posts],
         }));
    };

    return <PostDataContext.Provider value={state}>
        {children}
    </PostDataContext.Provider>
}

score:0

setState({ ...state, posts: [...payload,...state.posts] })

Related Query

More Query from same tag