Home > Mobile >  Type 'unknown[]' is missing the following properties from type 'InitialState'
Type 'unknown[]' is missing the following properties from type 'InitialState'

Time:11-15

Trying to work out how to pass types to value?

<Context.Provider value={[state, dispatch]}>{children} 
</Context.Provider>

Type 'unknown[]' is missing the following properties from type 'InitialState': navigateTo, user, avatar, dashBoardSelectedMenuItemts(2739) index.d.ts(338, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps' (JSX attribute) React.ProviderProps.value: InitialState

import React, { createContext } from "react";
import Reducer from "./reducer";

interface InitialState {
  navigateTo: string;
  user: string;
  avatar: string;
  dashBoardSelectedMenuItem: string;
}

const initialState: InitialState = {
  navigateTo: "dashboard",
  user: null,
  avatar: null,
  dashBoardSelectedMenuItem: "dashboard",
};
export const Context = createContext<InitialState>(initialState);

const Store = ({ children }) => {
  const [state, dispatch] = React.useReducer<any>(Reducer, initialState);

  return (
    <Context.Provider value={[state, dispatch]}>{children}</Context.Provider>
  );
};

export default Store;

Thanks for looking.

CodePudding user response:

Try this

import React, { createContext } from "react";
import Reducer from "./reducer";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

interface InitialState {
  navigateTo: string;
  user: string | null;
  avatar: string | null;
  dashBoardSelectedMenuItem: string;
}

const initialState: InitialState = {
  navigateTo: "dashboard",
  user: null,
  avatar: null,
  dashBoardSelectedMenuItem: "dashboard"
};

export const Context = createContext<[InitialState, React.Dispatch<any>]>([
  initialState,
  () => {}
]);

const Store = ({ children }) => {
  const [state, dispatch] = React.useReducer(Reducer, initialState);

  return (
    <Context.Provider value={[state, dispatch]}>{children}</Context.Provider>
  );
};

export default Store;

In your reducer add the type information for the state like below

export const Reducer = (state: InitialState, action:any): InitialState => {
  switch (action.type) {
    ...
    ...
  }
}

CodePudding user response:

Let me try to help you.

Here as you have defined the type os user and avatar in Initial state as string you should pass string only as value.

Perhaps you are passing null instead of an empty string "" could solve the type problem.

typeof null is Object.

const initialState: InitialState = { navigateTo: "dashboard", user: "", avatar: "", dashBoardSelectedMenuItem: "dashboard", };

You may visit this link for similar problem Using react context with react hooks in typescript

  • Related