What is the best way to transfer the information from my MYSQL database into a JSON array?

After setting up a MySQL database that I can query using ExpressJS and NodeJS, I found the following data structure:

id: 1
username: 'someUsername'
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9fedfef1fbf0f2daf2fef6f3dffaf2fef6f3b1faf2fef6f3">[email protected]</a>'

My goal now is to transform this database data into a JSON array, then iterate over it to display to the user. One approach I considered was populating the app's state. This involved creating a class component, adding a mapStateToProps function to assign the queried data to the state, and subsequently using this state data within the Reactapp itself. However, I am uncertain about the effectiveness of this method.

Answer №1

Here is a simple code snippet that demonstrates how to fetch data from a backend when the component loads, and then display the fetched data using .map without relying on redux (mapstatetoprops).

const DisplayData = () => {

     const [ data, setData ] = useState([]);

     
    const fetchDataFromBackend = async () => {
         const response = await fetch(url);
         const jsonData = await response.json();
         setData(jsonData);
    }

     useEffect(() => {
         fetchDataFromBackend()
     },[])

 return ( 
    <div>
        {data.map(item => <p>{item.name}</p>) }
        <pre>
            { JSON.stringify(data, null, 4) }
        </pre>
    </div>
}

Answer №2

When you receive the result data from your SQL query, it is in the form of an array containing objects. The key to utilizing this data effectively is by iterating through it and assigning it to a target object.

let sqlQueryData = returnSQLResults // retrieve data from SQL query
let jsonObject = {}

for (entry in sqlQueryData) {
  jsonObject[entry.id] = {
    id: entry['id'],
    name: entry['name'],
    age: entry['age']
  }

To access information within the JSON object, you can use

Object.keys(jsonObject).forEach(element => {
    // 'element' represents an object from the JSON array
}

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

Issue: TableHead inside an Expandable Row in MUI-Datatable is being duplicated for each row, causing the table to not be centered.Explanation: The

Can anyone help me with this issue? I'm having trouble with my table where the headings are repeating for every row and the table is stuck on the far right side. How can I center the table instead? Codesandbox: https://codesandbox.io/s/xenodochial-fo ...

Automatically identifying cloud functions ready for deployment with the gcloud command line interface

When utilizing Firebase tools, the deployment process is streamlined with auto-detection of available functions by issuing the command: firebase deploy --only functions However, for more extensive control over environment variables and VPC connectors, we ...

I encountered an issue when attempting to execute an action as I received an error message indicating that the dispatch function was not

I just started learning about redux and I am trying to understand it from the basics. So, I installed an npm package and integrated it into my form. However, when I attempt to dispatch an action, I encounter an error stating that 'dispatch is not defi ...

The Axios API request is made, but fails to retrieve any data back to the client

I've been working on a feature in my VueJS app where I need to restrict page viewing of an Upload instance to only members of a specific Group. However, I'm facing an issue with retrieving the group information. Despite axios successfully hittin ...

Creating a PHP script that retrieves data from JavaScript and stores it in MySQL can be accomplished by using AJAX to send the

Hello, I am attempting to create a PHP script that can extract coordinates from this JavaScript code (or from this link ) and store them in a MySQL database. Can someone please provide me with a tutorial on how to accomplish this? <script> var ...

When running fs.rmSync on Ubuntu, an error is thrown stating that undefined is not a

Attempting to remove a basic folder that contains another nested folder, such as: /tmp/ac6c1fcaeae0c7ec4d1a8/res. Here is the code I am using: module.exports.deleteFolder = (path) => { try { if (fs.existsSync(path)) { console.lo ...

styling a flex container with aligned text and buttons

I'm attempting to align text on the left and button controls on the right within a display: flex div. <CustomFieldContainer> <StyledWellContainer> <FieldDetails key={id}> <H4 bold>{label}</H4> <Styled ...

The npm ping feature is causing command prompt windows to open

I am currently working on a project that involves pinging certain IPs. I have opted to use the npm ping package for this purpose, which can be found at https://www.npmjs.com/package/ping. Initially, when I run the service, everything works perfectly fine. ...

I am eager to re-execute the query by simply clicking on buttons, however, it seems to not be functioning properly

export const useCustomLogin = (loginType) => { return useQuery({ queryKey: ['custom-login', loginType], // 'custom-login' is a simple function that uses axios get method queryFn: async () => await customLogin(loginTy ...

Utilizing MongooseJS's Find Method for Retrieving Data by Reference

Below is a Mongoose Schema that I am working with: var mongoose = require('mongoose') , dev = require('../db').dev(); var schema = new mongoose.Schema({ date: { type: Date, default: Date.now() }, company: { ty ...

When uploading files, a NodeJS application behind an Apache2 reverse proxy may encounter the error message "413 Request Entity Too Large."

I am currently working on a node.js application that allows users to upload large files. Everything runs smoothly when the application is accessed on port 8080 or 3000. However, when trying to access it on port 80 behind apache2 with mod_proxy set up as ...

Exclusive to Safari: Codesandbox is experiencing difficulties retrieving data from the localhost server

Would you mind helping me out with this technical issue I'm facing? For the server/API, I am using this link. As for the mock website, it can be found at this URL. The problem is that, in my code, I'm using axios to fetch data from the locally h ...

Storing the values of a React JS application in local storage using

Storing data received from the backend in local storage: async onSubmit(e){ e.preventDefault(); const {login, password } = this.state; const response = await api.post('/login', { login,password }); const user ...

Types are not appearing in @types/node

I have added @types/node to my project. In the index.ts file, the default node modules are being treated as type any. const fs = require('fs'); The type of fs is currently set to any. { "ts-node": { "cwd": "/User ...

Error occurred while making a request in React using Axios: TypeError - Unable to retrieve the 'token' property as it is undefined

After successfully receiving a token from logging in with React Redux, I attempted to authorize it using the token. However, an error occurred stating Axios request failed: TypeError: Cannot read property 'token' of undefined. The token is stored ...

List of Nodes with five links

I'm encountering an issue when trying to reference the final node. The expected output is: Linked List with 5 nodes Node Value: Head Node / Next Node Value: Second Node / Last Node Value: null Node Value: Second Node / Next Node Value: Third N ...

Struggling to locate the node module 'node:fs' while working with JavaScript and attempting to deploy to my personal Linux server

Error: Module 'node:fs' Not Found at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15) at Function.Module._load (internal/modules/cjs/loader.js:562:25) at Module.require (internal/modules/cjs/loader.js:692:17) a ...

Tips for transferring props and states between sibling components using react hooks

I am currently facing a challenge in passing props and states between different components. The parent component is rendering as shown below: const Countdown = () => { return ( <div> <Timer taskNumber={1} /> <ClickScore ...

Am I using Node.js, Express, and Promises correctly in my code?

In my Express route, I initially encountered an issue where input data passed through 3 different functions was being queued and returned one at a time. After some testing, I discovered this bottleneck and decided to refactor my code. I modified the functi ...

React-Toolbox: Attempting to horizontally align the Cards side by side

When working with React-Toolbox, I encountered an issue with aligning Card elements horizontally. I attempted using display: inline-block, which successfully separated them into three distinct cards as desired. However, they did not align next to one ano ...