[Fixed] How do I return an object array in an express function so that it can be rendered or displayed on the frontend?

Issue

//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 is a search function that goes to the backend and retrieves the data, which correctly works as the console shows the arrays that should return as shown below. I was informed by someone that the object below can’t be rendered straight up so I attempted to make the object "readable" through following some guides online but to 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)

This is the frontend page that is attempting to make the object render-able and display it on the web 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>
        )
   
    }
}

Solution

Ok, so for async promise use callback inside the promise resolve. Please have a look

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 result is of array type you are expecting
        callback(result);
    });
}

Leave a Reply

(*) Required, Your email will not be published