[SOLVED] Integrate interface to get function


This Content is from Stack Overflow. Question asked by prettyMaria

I am new to react and JavaScript and I want to integrate User interface into my UserContext so I can get my IsAdmin variable all along the project(to do some filters). Any ideas how I can do that? I ve tried different methods but I can’t get it right.

import axios from "axios";
import React, { useEffect, useState } from "react";
interface User{
    name: string;
  email: string;
  password: string;
  isAdmin: boolean;

export const UserContext = React.createContext<any[]>([]);
export const UserProvider = (props: any) => {
  const [user, setUser] = useState([]);
  useEffect(() => {
    // const loadedToken = localStorage.getItem("logInToken")
    //   ? localStorage.getItem("logInToken")
    //   : sessionStorage.getItem("logInToken");

    // const config = { headers: { Authorization: `Bearer ${loadedToken}` } };
      .then((res) => {
        const user = [];
        for (let key in res.data) {
          user.push({ ...res.data[key], id: key });
        // console.log(posts);
      .catch((err) => {
  }, []);

  return (
    <UserContext.Provider value={user}>{props.children}</UserContext.Provider>


You can type your user state variable like this

const [user, setUser] = useState<User[]>([]);

To type the context (where context is created)

const UserContext: React.Context<User> = createContext();

This Question was asked in StackOverflow by prettyMaria and Answered by axtck It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?