I have a button in react and when it is pressed, I would like to print the content of 2 concatenated arrays. This is the code for it
const QueryCalibDetail = ({result}) => {
const [success, setSuccess] = useState('')
const [raws, setRaws] = useState([])
const handleClick = async (e) => {
await axios.get('/api/rawsRoute/' + result.rawID)
.then ((json) => {
setRaws(json.data.raws)
})
const allFiles = result.config_files.concat(raws)
for (const fileID of allFiles) {
console.log(fileID)
}
To explain this code, QueryCalibDetail
takes a prop called result
which is a json and has fields _id
(an id), rawID
(an id) and config_files
(an array of ids). I use axios to get an element from a database with the id rawID
. The fetch returns a json which has a field raws
, an array of ids. Now I have 2 arrays of ids that I would like to concatenate and iterate through and log to console. However, the state raws
remains an empty array even after setRaws
has been called, and only the array provided by result.config_files
is printed. The concatenated array only gets printed when I click the button a second time.
This has been a recurring issue in my project, and I never understood why useState doesn't immediately update the state, or how to fix the issue. Can someone explain what I'm supposed to do in this scenario, since it seems to happen rather often and every time I don't know how to handle it.