TypeError: _this.child(key).get is not a function

Viewed 676

I'm using hookstate to import an array which is going to be stored in state.

I've got this initial object - import { createState } from "@hookstate/core";

const initialState = {
    exerciseDetails: [
        {
            exerciseID: 1,
            exerciseName: "ex name",
            exerciseDesc: "desc",
        },
    ],
};

const exerciseState = createState(initialState);
export default exerciseState;

And then I'm accessing the object in my functional component as -

function CreateWorkoutScreen(){
    const global = useState(exerciseState);
    const { exerciseDetails } = global.get();
}

Which gives me the following error - TypeError: _this.child(key).get is not a function. (In '_this.child(key).get()', '_this.child(key).get' is undefined)

However, if I change my initial state to

const initialState = {
        count: 0,
};

and access it in my functional component as

  function CreateWorkoutScreen(){
    const global = useState(exerciseState);
    const { count } = global.get();
}

It works as expected. I'm guessing I'm not getting access to the array properly? Am I using the wrong syntax here?

Thanks in advance!!

1 Answers

The problem is that you have not imported useState from @hookstate/core, but from React

const global = useState(exerciseState); //define global state locally with hookstate's useState method
const { exerciseDetails } = global.get();

const accessFunction = () => {
  const type1 = global.exerciseDetails.get(); //works
  const type2 = global["exerciseDetails"].get(); //works
  //const type3 = global[exerciseDetails].get(); //error
  const { exerciseDetails } = global.get(); //works
  return [exerciseDetails, type1, type2];
};

Also here is the working example: https://codesandbox.io/s/dry-field-vjp61?file=/src/App.js

Related