What is the best way to send an object array from an express function to be displayed on the frontend?

//search.js file

import axios from "axios";

export function storeInput(input, callback) {

  //input = document.getElementById("a").value;
  let result = [];

  console.log(input);   

  if (!callback) return;
  
  axios.post("http://localhost:4000/id", {
    searchWord: input,
  }).then((response) => {
    result = response.data;
    console.log(result);
  });

  callback([
    {
      result
    }
  ]);


}

This function is designed to retrieve data from the backend and display it properly. The data arrays are displayed in the console as shown below. I attempted to format the object for rendering on a webpage with no success.

[{…}]
0:
brand_name: "Lays"
calories: 160
calories_fat: 90
first_ingredient: "other"
processed: "yes"
product: "Classic potato chips"
saturated_fat: 2
serving_size: 28
short_name: "potato chips"
sodium: 170
sugar: 1
trans_fat: 0
_id: "60207f84a8241d2bb803423b"
__proto__: Object
length: 1
__proto__: Array(0)

Here is the frontend code attempting to render the object and display it on the page.

//snack-search.components.js file

import React, { Component } from 'react';
import {storeInput} from "./search.js";

const Snacks = props => (
    <tr>
        
        <td>{props.snacks.brand_name}</td>
        <td>{props.snacks.product}</td>
        <td>{props.snacks.short_name}</td>
        <td>{props.snacks.serving_size}</td>
        <td>{props.snacks.calories}</td>
        <td>{props.snacks.calories_fat}</td>
        <td>{props.snacks.saturated_fat}</td>
        <td>{props.snacks.trans_fat}</td>
        <td>{props.snacks.sodium}</td>
        <td>{props.snacks.sugar}</td>
        <td>{props.snacks.first_ingredient}</td>
        <td>{props.snacks.processed}</td>

    </tr>
)

export default class SnackSearch extends Component {
    constructor(props) {
        super(props);
            this.state = { snacks: null };
    }
    
    setSnackState(snacks = null) {
        this.setState({ snacks });
    }
    
    componentDidMount() {
        // make async call here not in render
        const callback = (snacks) => this.setSnackState(snacks);
        storeInput("Lays", callback);
    }

    SnackList() {
        const snacksList = this.state.snacks;
        return (
          snacksList &&
          snacksList.map((currentSnack, i) => (
            <Snacks snacks={currentSnack} key={i} />
          ))
        );
    }

    render() {

        return (
            <div className = "search">
                <table> {this.SnackList()}</table>
            </div>
        )
   
    }
}

Answer №1

Alright, when working with async promises, it's important to use a callback inside the promise resolve. Here is an example for you to check out.

search.js

/**
 *
 * @param {String} input
 * @param {Function} callback
 */
export function storeInput(input, callback) {
    let result = [];

    if (!callback) return;

    axios.post("http://localhost:4000/id", {
        searchWord: input,
    }).then((response) => {
        result = response.data;
        // If the result is of array type as expected, then execute the callback function
        callback(result);
    });
}

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

Customize the toggle icon for the accordion in Framework7

I took inspiration from the custom accordion elements provided in the documentation and made some alterations to the icons. However, I'm facing an issue with getting the toggle functionality of the icons to work properly. My goal is to have a "+" dis ...

Switching up the Label Colors in Chart.JS

It's been a while since my last question, so please bear with me if I'm not following the rules. I've attached my current code and a reference image of the chart. I am completely new to working with ChartJS. The situation is a bit unique: t ...

Experiencing a "non-serializable value found in the state" error specifically while utilizing redux toolkit, but this issue does not occur with traditional redux implementations

While transitioning my app to utilize Redux Toolkit, I encountered an error after switching over from createStore to configureStore: A non-serializable value was found in the state at path: `varietals.red.0`. Value:, Varietal { "color": "red", "id": " ...

How can I use AJAX to transmit a 2D array to a PHP page and then display each dimension individually?

Recently, I created a webpage with multiple checkboxes. Using jQuery, I am able to fetch data from these checkboxes and store them in a two-dimensional array. Here is an excerpt of my code: HTML snippet: <input type="checkbox" name="checkboxs[]" pric ...

When pasting Arabic text into an input box, the words in HTML appear to be jumbled and shuffled around

When I replicate this text يف عام and input it into a box, the output is shown as follows عام يف ...

Tips for accessing the "data" of a PHP array using AJAX

My code snippet using Ajax: $.ajax({ type: 'post', url: 'url.php', dataType: 'JSON', success: function(data) { id = // Need to extract the ID data from 'data' } }); ...

"Encountering a problem with compression in Kafka while using the Node.js client with

I am currently utilizing the kafka-node library to consume data from Kafka. It appears that the data I am receiving is compressed with SNAPPY. How can I decompress this data once it has been retrieved? I attempted to use the node-snappy library for decompr ...

What is causing the issue with Firebase not functioning on my Node.js server?

After reviewing the code below, I encountered an issue: var email = req.body.correo; var pass = req.body.pass; var firebase = require("firebase-admin"); var serviceAccount = require("./prueba-064cb79dba28.json"); firebase.initializeApp({ credential: fire ...

Do we need to use aria-labelledby if we already have label and input associated with "for" and "id"?

Here is the HTML structure for the Text Field component from Adobe Spectrum: The <label> element has a for attribute and the <input> has an id which allows screen readers to read out the label when the input is focused. So, why is aria-label ...

What is the best way to initially hide a div using slide toggle and then reveal it upon clicking?

Is there a way to initially hide the div tag and then animate it in a slide toggle effect? I attempted using display:none on my '.accordion_box' followed by show() in slideToggle, but this results in adding the CSS property display: block. My goa ...

Contrast in executing an Arrow Function versus a regular Function when passing them as Props in REACTJS

Here is the component code: <SelectCampanha titulo="Preenchimento obrigatório" listaOpcoes={ category ? riskModel.filter((item) => item.CategoryType.includes(categoria) ...

"Clicking on one item in the Bootstrap submenu doesn't close the other items,

I have this Javascript code snippet that deals with expanding and collapsing submenu items: <script type="text/javascript> jQuery(function(){ jQuery(".dropdown-menu > li > a.trigger").on("click",function(e){ var current ...

Interactive Timekeeping Tool with AngularJS Alarm Feature

I have successfully implemented the functionality to display the system time and date. Additionally, I have set up textboxes for users to input the time they want to set as their first alarm. My current goal is to trigger a particular action once the syst ...

Encountering the ERR_HTTP_HEADERS_SENT error while trying to send a response

Here is my request handler code exports.handleRequest = function (req, res, next) { var question = getQuestion(); console.log('request handler page'); var response = res.json([{"message": `${question}`}]); console.log(` ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

Checkbox enabled Bootstrap image

I am encountering a minor issue where I am attempting to incorporate a simple image that can be toggled on and off by clicking on it. After coming across some bootstrap code online, I decided to test it in my project. Unfortunately, the code does not seem ...

How come once I close a PrimeNG modal that is defined within a child component, I am unable to reopen it?

Currently, I am developing an Angular application that utilizes PrimeNG. In the process, I encountered a challenge. Initially, I had a component with a PrimeNG Dialog embedded within (refer to this link), and it was functioning properly. To streamline my ...

Displaying only one modal at a time with Bootstrap 3

The code snippet below is used to trigger my newsletter modal: $(window).load(function(){ if (sessionStorage.getItem("is_seen") === null) { setTimeout(function(){ $('#newsletter_modal').modal('show&ap ...

How to resolve a TypeError saying "Object(...) is not a function"?

I've been attempting to display material-ui tabs as a component on another page, but I'm encountering an error that causes the code to break when loading the page with this component. I've tried two different methods of rendering this compo ...

Prisma Hack: excluding properties in type generation

EDIT hiding fields in the TypeScript definitions may pose a hidden danger: inaccessible fields during development with intellisense, but accidentally sending the full object with "hidden" fields in a response could potentially expose sensitive data. While ...