Github
같잖은 쇼핑 목록을 출력하고
하위목록을 조회하고 아이템을 등록한다
Context와 Provider, Consumer에 대한 내용을 다룬다
// Context Provider export const SomeContext = createContext(); export const SomeContextProvider = ({ children }) => { return ( <SomeContext.Provider value={{ value: someValue }}> { children } </SomeContext.Provider> ); }
// Context Consumer <SomeContextProvider> <SomeContext.Consumer> { ({value}) => { return ( {children.map(child => ( <Child value={value}/> )} ); }} </SomeContext.Consumer> </SomeContextProvider>
대충 이런식
여기에 flux 패턴을 조합하여
// Context Provider export const SomeContext = createContext(); const initialValue = { value: {}, error: '' }; const reducer = (value, action) => { switch(action.state) { case 'SUCCESS': return { ...value, value: action.data, error: false }; case 'FAIL': return { ...value, value: false, error: action.data }; default: return value; } }; const SomeContextProvider = ({ children }) => { const [value, dispatch] = useReducer(reducer, initialValue); const doNeedToCreateValue = () => { try { const someValue = createValue(); dispatch({ state: 'SUCCESS', data: someValue }); } catch(error) { dispatch({ state: 'FAIL', data: error.message }); } }; return ( <SomeContext.Provider value={{ ...value, doNeedToCreateValue }}> { children } </SomeContext.Provider> ) }
// Context Consumer <SomeContextProvider> <SomeContext.Consumer> {({ value, error, doNeedToCreateValue }) => { return children.map(child => ( <Child value={value} error={error} doNeedToCreateValue={doNeedToCreateValue}/> )); }} </SomeContext.Consumer> </SomeContextProvider>
대충 이런식으로 변경
그러나 Consumer를
저렇게 사용할 필요가 없었고
받는쪽에서...
그러니까 지금의 경우엔
Child가 useContext를 사용해서
값을 받을 수 있다
// Context Consumer <SomeContextProvider> {children.map(child => ( <Child/> ))} </SomeContextProvider>
// Child const Child = () => { const { value, error, doNeedToCreateValue } = useContext(SomeContext); return (<do> <what> <the> <fuck> <child> <want/> </child> </fuck> </the> </what> </do>); }
이런식
구체적인 사용은 다른 내용을 참고해봐야 할것 같다
진짜 정리하는 것 도 일이다
피곤하다 진짜