jarwin
jarwin

Reputation: 668

How to change this file from class to hooks?

I'm trying to change this file https://github.com/wix/react-native-calendars/blob/7aefe01f0e18df4272ae0d1d9990af196e30cc17/example/src/screens/agenda.js#L8 to hooks but i'm having a hard time trying to figure out to make setItems visible to the function loadItems Thats what I tried to do so far https://pastebin.com/JSzbJLqV

I have my state const [items, setItems] = useState({});

And I want to make it visible to this function const loadItems = (day) => { ...

I'm getting this error: ReferenceError: Can't find variable items

Upvotes: 1

Views: 59

Answers (2)

Aditya Ramariya
Aditya Ramariya

Reputation: 11

states in hooks can be used to the function it is defined at! make loadItems function as a helper function inside Calendar function itself, then you are able to use your state [items, setItems] into loadItems function as well

like this:

 const Calendar = () => {
 const [items, setItems] = useState({});
  const loadItems = day => {
    setTimeout(() => {
      for (let i = -15; i < 85; i++) {
        const time = day.timestamp + i * 24 * 60 * 60 * 1000;
        const strTime = timeToString(time);
        if (!items[strTime]) {
          items[strTime] = [];
          const numItems = Math.floor(Math.random() * 3 + 1);
          for (let j = 0; j < numItems; j++) {
            items[strTime].push({
              name: "Item for " + strTime + " #" + j,
              height: Math.max(50, Math.floor(Math.random() * 150))
            });
          }
        }
      }
      const newItems = {};
      Object.keys(items).forEach(key => {
        newItems[key] = items[key];
      });
      setItems(newItems);
    }, 1000);
  };

  return (
    <div
      items={items}
      loadItemsForMonth={loadItems}
      selected={"2020-05-16"}
      rowHasChanged={rowHasChanged}
    />
  );
};

I hope this helps.

Upvotes: 1

Vivek Doshi
Vivek Doshi

Reputation: 58543

Issue :

loadItems function is outside of const Calendar = () => { , and items variable scope is within that function only not outside of it and you are trying yo access it from outer function.

const Calendar = () => {

    const [items, setItems] = useState({});
    ...

}

const loadItems = (day) => {
   ....
   // you are trying to access `items` inside it
   if (!items[strTime]) {
   ...
}

Solution :

const Calendar = () => {

    const [items, setItems] = useState({});

    // put it inside the functional component
    const loadItems = (day) => {
       ....
    }

}

Upvotes: 1

Related Questions