React Typescript Move loading data vom component to context

Viewed 44

On my component/page/homepage component I am getting a type Profil.

It is declared like this:

interface HomePageState {
  profile: Profil | undefined
}

const [state, setState] = useState<HomePageState>({
    profile: undefined,
  })

...
const { loadProfile } = useProfile()
...
const userProfile = await loadProfile()

   ...
    .then(() => {
      setState(() => {
        return {
          profile: userProfile || undefined,
        }
      })
      return resolve(true)
    })
    .catch((err) => {
      console.error('failed to load data', err)
    })
})

My goal is to move this into context, so once the profile is declared it goes through every component. How do I convert this code into a context setting?

1 Answers
export const MyContext = createContext(null);


<MyContext.Provider value={{state}}>
  <Component1 />
</MyContext.Provider>

And inside every component import myContext and just use the context like this:

const ctx = useContext(myContext);

Now you can use ctx.

Related