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
I found this solution by changing
to
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.
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 onbookables.bookables
(the first bookables refers to the imported data, and the second bookables refers to the array bookables inside the JSON data).worked because, in the import you are calling the JSON Data as
data
, and in the next line, you are extracting the propertybookables
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 invokingfilter
on the array element inside the JSON object.Hope this helps