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}`);
});
CodePudding user response:
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.