import React, { useReducer } from "react" import axios from "axios" import BGTContext from "./bgtContext" import BGTReducer from "./bgtReducer" import { GET_COLLECTION, GET_SECTIONS, SET_LOADING } from "../types" const BGTState = props => { const initialState = { sections: [], collection: {}, loading: false, } const [state, dispatch] = useReducer(BGTReducer, initialState) // Ottiene le sezioni della navbar const getSections = async () => { try { setLoading() const res = await axios.get( ${process.env.API_URL}/sections?_sort=order:ASC ) dispatch({ type: GET_SECTIONS, payload: res.data, }) } catch (err) { dispatch({ type: GET_SECTIONS, payload: err.response.msg, }) } } // Ottiene la collezione tramite il riferimento const getCollection = async id => { try { setLoading() const res = await axios.get(${process.env.API_URL}/collections/${id}) dispatch({ type: GET_COLLECTION, payload: res.data, }) } catch (err) { console.log(err) } } const setLoading = () => dispatch({ type: SET_LOADING }) return ( <BGTContext.Provider value={{ sections: state.sections, loading: state.loading, collection: state.collection, getSections, getCollection, }} > {props.children} </BGTContext.Provider> ) } export default BGTState
Обсуждают сегодня