Struggling to map a JSON file in a NextJS project using Typescript

I'm a beginner in JS and I'm currently struggling to figure out how to display the data from a json file as HTML elements.

Whenever I run my code on the development server, I encounter the error message: "props.books.map is not a function".

I suspect that the format of my json file might be causing this issue, as it doesn't seem to match what .map requires. (I'm unsure about the correct structure for static json files since there are various examples online. If anyone has resources on industry standard json file formats, I would greatly appreciate it!)

Here's a snippet of the json file:

./static/bookReviews.json

Below is the code where I attempt to map the json file:

./pages/content/books.tsx

import NavBar from "@/components/NavBar";
import { NextPage, GetStaticProps } from "next";

const Books: NextPage<{
  books: {
    author: string;
    dateFinish: string;
    dateStart: string;
    rating: string;
    review: string;
    title: string;
  }[];
}> = (props) => {
  return (
    <div className="justify-between items-center bg-gradient-to-b from-slate-600 to-slate-900 p-10 w-screen h-screen">
      <NavBar />
      <h1>Books</h1>
      

      {props.books.map((x) => {
        return <p>{x.title}</p>;
      })}
    </div>
  );
};

export const getStaticProps: GetStaticProps = async () => {
  const books = (await import("../../static/bookReviews.json")).default;

  return {
    props: { books },
  };
};

export default Books;

If you need more information to help me with this issue, please let me know.

Any assistance would be highly appreciated :)

Answer №1

After some troubleshooting, I finally figured it out! I realized that when I imported the json file, I forgot to specify the Books component. In the json file, the key is "Books" and its value is an array of dictionaries containing book information. Once I made this adjustment and specified the array, everything started working correctly with the .map function.

Here's the change I implemented:

const books = ((await import("../../static/bookReviews.json")).Books);

A huge thank you to @crashmstr for guiding me in the right direction!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js: Steps for receiving an ArrayBuffer in a $http request

I made a request using $http.post from Angular.js to Node.js, expecting to receive an ArrayBuffer. Here is the code snippet: $http.post('/api/scholarships/load/uploaded-files', Global.user, {responseType:'arraybuffer'}).success(functi ...

What steps are involved in setting up a point distribution system in AngularJS?

My objective is to develop a point allocation system within AngularJS. I have successfully created a basic directive that introduces DOM elements, including a span displaying "0" points and buttons for incrementing and decrementing. The total number of poi ...

Troubleshooting the NullInjectorError in Angular - Service Provider Missing?

I'm facing an issue in my code where I have buttons that should trigger pop-ups displaying details as a list when clicked. However, every time I click the buttons, I encounter the error mentioned below. It seems like I am unable to access the desired ...

The performance of ternary operators in Typescript-based Reactjs fell short of my expectations

As a newcomer to TypeScript+ReactJS, I am facing an issue with the Ternary operator in my code. Here is the code snippet: import React, { SyntheticEvent,useRef,useState } from "react"; import Result from './Result'; //main application c ...

Is it possible to enhance the readability of "json_encode" results using <br> tags?

My statement results were being echoed as a JSON object, but when using the json_encode() function, everything was outputted into a single line like this: {"0":{"username":"Olli"},"1":{"username":"Heiner"},"2":{"username":"Rolf"},"success":true,"rowcount" ...

What is the best method for displaying a radio button as selected based on a variable value?

I have a variable that stores the value of a radio button. After checking certain conditions, I want to dynamically select the radio button based on this value. if(cheque_date == system_date) { cheque_value='Current'; } else { cheque_value ...

Issue: MUI Autocomplete and react-hook-form failing to show the chosen option when using retrieved information

The MUI Autocomplete within a form built using react hook form is causing an issue. While filling out the form, everything works as expected. However, when trying to display the form with pre-fetched data, the Autocomplete only shows the selected option af ...

Display problem with Backbone view

I'm having trouble loading views on my page while using underscore for templating. I've tried navigating to the page and loading the view in the initialize function, but neither approach has worked. The majority of this code is from an example. ...

Transmit data from parent page to child components in Nextjs

Is it possible to pass the props from a page to all other components in my application? I have set up a dynamic route structure that looks like this: -pages -[tv] -index.js -category -index.js ... The route is defined as: pages/[tv]/category ...

Using blending modes with gradient colors in an SVG design

I'm struggling to get my logo to change colors upon scrolling into a button with similar gradient colors, but I just can't seem to make it work. Can anyone lend me a hand? Thank you! Take a look at my Logo. I've attempted to add some styles ...

A guide to transforming Gremlin query outputs into Pandas or Python data structures

Seeking to enhance the appearance of my Gremlin query results by transforming them into dataframes. The output from Gremlin queries often resembles Json format, especially seen in examples like the answer to one of my previous questions that involves the ...

Jquery scripts seem to have a hit-or-miss success rate

Recently, I added a couple of Jquery scripts in my header to handle the fading in of a specific CSS class and scrolling down another one. Both of these classes are initially set to display: none in CSS, with Jquery responsible for making them visible. Here ...

Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText&g ...

Tips for overriding ng-disable in AngularJSUnleashing the

This is a comment box using AngularJS: <tr> <td colspan="5"><br/>Comments* <div><textarea class="form-control" rows="3" cols="60" ng-model="final_data.drc_scope" placeholder="Add comments here" ng-disabled="is_team==0 || isDis ...

Establishing the Initial State of React Context with Data from Apollo Query

In my React.js project, specifically with Next.js, I have implemented a global React context for managing user data. Here is how the context is structured: const UserContext = createContext<{ user: User | undefined; setUser: (u: User | undefined) =& ...

When using Gson to deserialize a map key, it anticipates an object

I encountered the following error message: Exception in thread "main" com.google.gson.JsonParseException: Expecting object found: "com.shagie.app.SimpleMap$Data@24a37368" whenever I attempt to deserialize a Map with complex keys: package com.shagie.app ...

Javascript - Unable to update button text

I am encountering a problem with updating the text of a Bootstrap button when a collapsed element is opened or closed. The icon part is updating successfully, but I am struggling to get the button text to update and I cannot figure out why. My knowledge o ...

"Apple TV now features an iOS app that allows users to watch YouTube videos

I am interested in developing an iOS application that can play YouTube videos in a UIWebView window. Users should have the option to play the videos directly on their iOS device or stream them via AirPlay to an AppleTV. The content displayed in the UIWebV ...

The Web Browser is organizing CSS elements in an alphabetized sequence

map.css({ 'zoom': zoom, 'left': map.width()/(2*zoom) - (point[0]/100)*map.width(), 'top': map.height()/(2*zoom) - (point[1]/100)*map.height() Upon observation, it appears that Chrome adjusts the map zoom first be ...

Transmit the identifier of the span tag to the URL seamlessly without the need to refresh

<div id="unique50">Greetings</div> Transfer the code 50 to the designated link by clicking on the specific div element without requiring a page reload ...