Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

react context api

import { createContext, useContext, useReducer } from "react";

const Actions = {
	SET_ITEMS: "SET_ITEMS",
};

const reducer = (state, action) => {
	if (action.type === Actions.SET_ITEMS) {
		return { ...state, items: action.payload };
    }

	return state;
};

const initialState = {
	items: []
};

const SimpleContext = createContext(initialState);
export const useSimpleContext = () => useContext(SimpleContext);
export const SimpleProvider = ({ children }) => {
	const [state, dispatch] = useReducer(reducer, initialState);

	function setItems(items) {
		dispatch({ type: Actions.SET_ITEMS, payload: items });
	}

	return <SimpleContext.Provider value={{ state, setItems }}>{children}</SimpleContext.Provider>;
};
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #react #context #api
ADD COMMENT
Topic
Name
9+1 =