Handling JSON Objects with Next.js and TypeScript

Currently, I am working on a personal project using Next.js and Typescript. Within the hello.ts file that is included with the app by default, I have added a JSON file. However, I am facing difficulties in mapping the JSON data and rendering its content. The JSON data is currently stored within a useState hook, but when attempting to manipulate it, both the browser and console display errors.

Below is the example of the hello.ts file containing a smaller JSON dataset located at /pages/api/hello:

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
  clientName: string
  campaignName: string
  userName: string
  frames: {
    id: string
    asset: string
    subheading: string
    description: string
    link: string
  }[]
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  res.status(200).json({
  userName: "username",
  frames: [
      {
          id: "1",
          asset: "",
          subheading: "Instagram",
          description: "",
          link: "someurl.com"
      },
      {
          id: "3",
          asset: "",
          subheading: "Facebook",
          description: "username Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean sollicitudin metus vitae",
          link: "someurl.com"
      }
  ] })
}

This is where the API call is made, located in components/container:

import { useEffect, useState } from "react";

import { FrameContainerProps } from "../../types";

const FrameContainer: React.FC<FrameContainerProps> = () => {
    const [apiDetails, setapiDetails] = useState<any>();

    useEffect(() => {
        fetch('http://localhost:3000/api/hello')
          .then((res) => {
            return res.json();
          })
          .then(
            (data) => {
                setapiDetails(data);
            },
            (err) => {
                return console.error(err);
            }
          );
    }, []);

    return (
        <>
            {Object.entries(apiDetails).map(detail => (
                <h3>{detail.frames[i].description ? detail.frames[i].description : ''}</h3>
            ))}
        </>
    )
}

export default FrameContainer;

Additionally, I am seeking guidance on how to only render the data if it contains values.

Answer №1

Ensure the default value of apiDetails is set to null and include a validation check to determine if the data has been loaded.
Additionally, remember to utilize the map function on apiDetails.frames:

import { useEffect, useState } from 'react';

import { FrameContainerProps } from '../../types';

const FrameContainer: React.FC<FrameContainerProps> = () => {
  const [apiDetails, setapiDetails] = useState<any>(null);

  useEffect(() => {
    fetch('http://localhost:3000/api/hello')
      .then((res) => {
        return res.json();
      })
      .then((data) => {
        setapiDetails(data);
      })
      .catch((err) => {
        return console.error(err);
      });
  }, []);

  if (!apiDetails) return <>Loading data...</>;

  return (
    <>
      {apiDetails.frames && apiDetails.frames.map((frame) => (
        <h3>
          {frame.description || ''}
        </h3>
      ))}
    </>
  );
};

export default FrameContainer;

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

Validating minimum and maximum values with Angular 2 FormBuilder

I am currently developing a form using Angular 2 Formbuilder and I want to ensure that users can only input positive values into the amount field (with a minValue of 0 and maxValue of 100). How can I go about implementing minimum and maximum value validati ...

Error in Laravel: The class 'AppHttpControllersResponse' was not found

Hi there, I've encountered an issue while working with Laravel 5. When trying to get a json response from my 'funcionarios' table, I received this error message: Class 'App\Http\Controllers\Response' not found. As a ...

How can I modify the color of a div when a validation error occurs?

I have recently completed a contact form with validation using the constraint validation api. Although the files are functioning as intended, I am curious if there is a method to make the error boxes turn red when an error occurs and white (or hidden) when ...

How can we initiate the AJAX request right away while also making sure the page is fully loaded before adding

One trick I've discovered is that by submitting an AJAX request in the <head> section of my webpage, I can avoid a minor flicker on page load when loading content via AJAX. Of course, this method still needs some refining to handle longer AJAX r ...

Using the Spread Operator to modify a property within an array results in an object being returned instead of

I am trying to modify the property of an object similar to this, which is a simplified version with only a few properties: state = { pivotComuns: [ { id: 1, enabled : true }, { id: 2, enabled : true ...

Determine the scroll location using NextJS

I'm trying to determine if the user has scrolled in order to update the UI using NextJS. I have come across various examples with similar code, such as this one: const [scrollY, setScrollY] = useState(0); const onScroll = (event) => { cons ...

A guide on utilizing portals in Next.js to move a child element beyond its direct parent container

Current Setup Wrapper export const ContainerComponent = () => { return (<ChildComponent/>); } Child Component export const ChildComponent = () => { return ReactDOM.createPortal( <aside> <div>{"I am a c ...

Tips for creating an Angular component that can receive a single value from a choice of two different lists

My angular component requires a value that belongs to one of two lists. For example: @Input() public type!: enumA | enumB; However, this setup becomes problematic when the enums share values or are linked together in a way I find undesirable. I would pre ...

Adjusting the height of a textarea within a table

My textarea's height is supposed to be 500%, but it's not changing. I suspect that being inside a table might have something to do with the issue, but I'm unsure of what needs to be adjusted to set the height correctly. Surprisingly, the wid ...

Error: The function scrollIntoView is invalid and cannot be found

I'm currently new to working with react-testing-library / jest and trying to create a test that checks if the route navigation (using react-router-dom) is functioning correctly. I've been following the guidance from the README as well as this hel ...

Having trouble sending a x-www-form-urlencoded POST request in Angular?

Despite having a functional POST and GET service with no CORS issues, I am struggling to replicate the call made in Postman (where it works). The only thing I can think of is that I may have incorrectly set the format as x-www-form-urlencoded. When searchi ...

Tips for delaying the execution of numerous ajax success callbacks?

In my JavaScript code, I am facing the following situation: call_A(success_A) call_B(success_B) function call_A(success){ // make ajax request success(result) } function call_B(success){ //make ajax request success(result) } function success_A(){ ...

Disable the default page scrolling behavior when collapsing an accordion section in Bootstrap 4 framework

Incorporating a Bootstrap 4 accordion with an expanded body section that causes the content below to scroll up when collapsed. To address this issue, attempting to scroll to the top of the clicked header and prevent undesirable scrolling from the collapse ...

Is there a way to grab the inner content of an e-mail link by right-clicking on it?

I am currently developing a Chrome Extension that functions similarly to the "Search on Google" feature when you right-click on selected text. However, I am facing an issue with making it work when right-clicking on a mailto: email link. How can I extract ...

Retrieve an instance of the property class within a property decorator

I'm attempting to create a decorator called @Prop that will assist me in adjusting attributes for custom elements. This is the desired code: class MyCustomClass extends HtmlElement { get content() { return this.getAttribute('content&apo ...

Simulated database in a Service using TypeScript with Node

Struggling with a unit test, I need to mock the this.orderRepository.findById(id); method to find an object by its ID. Although I've set the return value, the test keeps failing. This is my first time creating a unit test in Node using TypeScript and ...

Issue with by.cssContainingText function not performing as intended

I have a container that I want to be able to click on. Here's how it looks: <div class="CG-Item CG-B-Left ng-binding" ng-bind="SPL.showTitleText">My New SPL</div> So I am trying to use this code to click on it: element(by.cssContainingT ...

A Guide to Utilizing Parameters in Javascript Strings

I'm in search of a solution but struggling to find a comprehensive explanation. I am working on a code where I need the flexibility to easily update strings or other parameters. What I aim for is passing values to a string when calling it through a ...

Top method for showcasing animated images (HTML/CSS/JS)

For my website, I want to create an engaging animation showing a coin being flipped multiple times in the air before landing on a specific side. After the animation finishes, I would like it to transform into a static image of the final result. I've ...

Difficulty with BCRYPT retrieving information from MySQL

As a beginner in programming, I've hit a roadblock and can't seem to find any solutions. I've managed to successfully register users into my database and hash their passwords. Now, I'm trying to implement a login feature for these users ...