0

I am trying to get the names displayed of a 'Crate' (a crate full of records/albums), derived from a local JSON file. But it's not showing up. Should I be using params? Should I have not stringified the JSON? VSC tells me Property 'data' does not exist on type String. Before this I received an error that crates.map is not a function, indicating that the JSON was an object not an array.

public/data.json

    "crates": [{
            "id": 1,
            "nameCrate": "Pauls crate",
            "albums": ["Blue Bossa", "Boogarins"]
        },
        {
            "id": 2,
            "nameCrate": "Lauras crate",
            "albums": ["ABBA", "Blof"]
        }
    ]
}

index.tsx

import { useState, useEffect } from 'react'

export default function Home() {

  interface Crate {
    id: string;
    nameCrate: string;
    albums: string;
  }

  const [crates, setCrates] = useState<Array<Crate>>([]);

  useEffect(() => {
    fetch('data.json',{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    })
    .then((res) => res.json())
    .then((resJson) => {const data = JSON.stringify(resJson)
    setCrates(data.data)})
  }, [])

  console.log(crates)



  return (
    <div>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

<main>
  Main
  {crates && crates.map((crate) => (<div key={crate.id} {...crates}>{crate.nameCrate}</div>))}

</main>

      <footer className="bg-black">
       <div>This is the footer </div>
      </footer>
    </div>
  )
}

1 Answer 1

1

No need to stringify since response is json

{ 
    const data = resJson.crates
    setCrates(data)// set crates 
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.