PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 12, 2022

[FIXED] How do I import object data in an array in order using axios?

 October 12, 2022     axios, javascript, node.js, reactjs, typescript     No comments   

Issue

Currently, I can only recall certain arrays. I put the 'length' of the data in '[], but only the last data comes out. (I know why)

How do I sequentially import data from the first object to the last object in an array?

p.s DB: mySQL

  • Axios code to load data from the first array
 const getList = async () => {
    axios.defaults.withCredentials = true;
    const config = {
      headers: {
        withCredentials: true,
      },
    };
    try {
      //Successful response
      const response = await axios.get("url", config);
      const data = response.data;
      console.log(data);
      const id = data[0].BOARD_ID;
      const title = data[0].BOARD_TITLE;
      const register = data[0].REGISTER_ID;
      const date = moment(data[0].REGISTER_DATE).format(
        "YYYY MM DD, H:mm:ss a"
      );
      setBbsData([
        {
          ...bbsData,
          id: id,
          title: title,
          register: register,
          date: date,
        },
      ]);
    } catch (error) {
      //Failed to respond
      console.log(error);
    }
  • server code
app.use(cors({ credentials: true, origin: true }));

// api
app.get("url", (req, res) => {
  const sqlQuery = "SELECT *FROM BOARD;";
  db.query(sqlQuery, (err, result) => {
    res.send(result);
  });
});

app.listen(PORT, () => {
  console.log(`running on port ${PORT}`);
});

Solution

Arrays have a map method which allows you to operate on all its elements.

setBbsData(
  data.map((item) => ({
    id: item.BOARD_ID,
    title: item.BOARD_TITLE,
    register: item.REGISTER_ID,
    date: moment(item.REGISTER_DATE).format("YYYY MM DD, H:mm:ss a"),
  })),
);

Here we're taking each item and mapping them to a new object. The parentheses around the brackets are required or else it will be interpreted as a function body and not an object.



Answered By - caTS
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing