Skip to content

Instantly share code, notes, and snippets.

@OscarGM40
Last active December 2, 2022 07:56
Show Gist options
  • Save OscarGM40/804ebcf5c402f837c3f1c8437d7ceb09 to your computer and use it in GitHub Desktop.
Save OscarGM40/804ebcf5c402f837c3f1c8437d7ceb09 to your computer and use it in GitHub Desktop.
React ContextAPI(ejemplo con Typescript)
VIDEO 212-213 INICIO - CREANDO EL CONTEXTO DE LUGARES
Se sugiere usar tres archivos por cada Contexto que use(context/places,context/auth,context/ui,...):
* Uno para el createContext(PlacesContext.ts):
import { createContext } from "react";
export interface PlacesContextProps {
isLoading: boolean
userLocation?: [number, number]
}
export const PlacesContext = createContext({} as PlacesContextProps);
* Otro para el Provider:
import { PlacesContext } from "./PlacesContext";
export interface PlacesState {
isLoading: boolean;
userLocation?: [number, number];
}
const INITIAL_STATE:PlacesState = {
isLoading: true,
userLocation: undefined
};
type Children = {
children: JSX.Element | JSX.Element[]
}
export const PlacesProvider = ({ children }:Children) => {
return (
<PlacesContext.Provider value={{
isLoading: INITIAL_STATE.isLoading, <- no es importante,es un paso inicial,será sustituido por ...state
userLocation: INITIAL_STATE.userLocation,
}}>
{children}
</PlacesContext.Provider>
);
};
* Otro para la función pura reductora(fijate que el createContext y éste no devuelven JSX):
import { PlacesState } from "./PlacesProvider";
type PlacesAction = {
type: "setUserLocation",
payload: [number, number]
}
export const placesReducer = (state: PlacesState, action: PlacesAction): PlacesState => {
switch (action.type) {
case "setUserLocation":
return {
...state,
isLoading: false,
userLocation: action.payload
}
default:
return state;
}
}
Para usar la función hay que usar el hook useReducer y estarcir el state en el value:
export const PlacesProvider = ({ children }: Children) => {
const [state, dispatch] = useReducer(placesReducer, INITIAL_STATE);
return (
<PlacesContext.Provider
value={{
...state,
}}
>
Fijate que con esparcir el state fue suficiente.En un punto alto óptimo abastezco a la app:
* En el App.ts(en este caso se llamó MapsApp en vez de App)
import { PlacesProvider } from "./context"
export const MapsApp = () => {
return (
<PlacesProvider>
punto de entrada a la app
</PlacesProvider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment