skip to Main Content

I am doing the exercises in John Larsen’s book React Hooks in Action, chapter 2. When I clone his repository, the react app starts successfully. However, when I write it myself (and check again that I did not overlook any piece of code), I get an error.

Here’s my minimal code to reproduce the problem :

My project’s structure is

public
  index.html
src
  components
    App.js
  index.js
  static.json
package.json
  

The content of static.json is copied from his git repo.

Here’s the content of App.js

import {bookables} from "../static.json";

export default function App() {
  const bookablesInGroup = bookables.filter(b => b.group === "Room");

  return ( <p>Hello</p>  )
}

And I get the following error

ERROR in ./src/components/App.js 7:27-43
export 'bookables'.'filter' (imported as 'bookables') was not found in '../static.json' (possible exports: 0, 1, 2, 3, 4, 5)

My first idea was to add an export in static.json, but it’s clearly not the solution. It’s driving me crazy. What did I overlook ? Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    I found this solution by changing

    import {bookables} from "../static.json";
    

    to

    import data from "../../static.json";
    ...
    const { bookables } = data;
    

    I found the answer in https://stackoverflow.com/a/73143324/471461 and ES6 Destructuring and Module imports.

    It seems that I mixed between named imports and destructuring in the import statement, though I don't know why the exemples in the book work.


  2. bookables is a property inside the JSON data. filter is a function available for array objects.
    In your previous case, you imported bookables from the static JSON, and it was referring to the JSON data. In that case you had to do filter on bookables.bookables (the first bookables refers to the imported data, and the second bookables refers to the array bookables inside the JSON data).

    import data from "../../static.json";
    ...
    const { bookables } = data;
    

    worked because, in the import you are calling the JSON Data as data, and in the next line, you are extracting the property bookables from the JSON data. And, bookables is now an array and you are able to invoke filter on it.

    In short, in the first case you were trying to invoke filter on the JSON object, and in the working scenario, you are invoking filter on the array element inside the JSON object.

    Hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search