How to load initial data from api when using react-tracked provider?
vladakg85 opened this issue · comments
I my naive context implementation when I was setting provider I get categories data from api with:
const { data } = useGetCategories();
Now I want to use the same with this library:
import { useState } from 'react';
import { createContainer } from 'react-tracked';
import useGetCategories from '../hooks/useGetCategories';
import { Category } from '../@types/global';
export type State = {
categories: Category[];
};
const useValue = (): [State, React.Dispatch<React.SetStateAction<State>>] => {
const { data } = useGetCategories();
const [state, setState] = useState<State>({ categories: data || [] });
if (data && data !== state.categories) {
setState({ categories: data });
}
return [state, setState];
};
export const {
Provider,
useTrackedState,
useUpdate: useSetState,
} = createContainer(useValue);
Are there any drawback to my implementation?
So what I am trying to do is to set categories from api as soon as context use.
Is there better way to do this or this one is correct?
If I assume your naive impl with React Context doesn't have setState
, it would be something like this:
import { useState } from 'react';
import { createContainer } from 'react-tracked';
import useGetCategories from '../hooks/useGetCategories';
const useValue = () => {
const { data } = useGetCategories();
const setState = () => {
throw new Error('not implemented');
};
return [data, setState];
};
export const {
Provider,
useTrackedState,
} = createContainer(useValue);