1

So I have a database that I can query using ExpressJS and NodeJS. The Database is a MySQL db. and the data within looks like this:

id: 1
username: 'someUsername'
email: '[email protected]'

I want to somehow put the data from within the database into a JSON list and then map over it and show it to the user. Another option to achieve this, I reasoned, would be to populate the state of the app. I've thought of creating some class component, adding a mapStateToProps and assign the data returned from the queries to the state and then use the data from the state in the Reactapp itself. I am not so sure if that would be effective.

2 Answers 2

3

This is the minimum code example for a component that fetches data from your backend onLoad, and displaying the data using .map, without using redux (mapstatetoprops)

const DisplayData = () => {

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

     
     const fetchData = async () => {
         const results = await fetch(url).then(res => res.json());
         setData(data)
     }

     useEffect(() => {
         fetchData()
     },[])
 return ( <div>
           { data.map(item => <p>{item.name}</p> }
           <pre>
             { JSON.stringify(null, data, 4) }
          </pre>
         </div>
}
Sign up to request clarification or add additional context in comments.

Comments

2

Well, the return data that you get from the SQL query is itself an array of objects, Your answer lies in simply iterating over the returned data and assigning it to whatever object you like.

let queryResults = returnedQueryData // data returned from SQL query
let jsonarray = {}

for (row in queryResults) {
  jsonarray[row.id] = {
    id: row['id'],
    username: row['username'],
    email: row['email']
  }

To access data from the JSON array use

Object.keys(jsonarray).forEach(e => {
    // Here e is the object element from the JSON array
}

1 Comment

is jsonarray not being overwritten each time in the loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.