I’m new to Axio and React, I would like to know how to return my results from Axio.
My console.log shows all my arrays send by PHP perfectly but it won’t return in my HTML code.
Here is my code
axios.get('api.php').then(result => {
console.log(result.data);
return result.data
});
I tried using innerHTML but it’s giving me
[object Object]
And adding .macdb
after result.data
gives me an undefined
Presumably you are trying to display the returned data in some meaningful way. In react this is accomplished by rendering some JSX from state and/or props. With async data fetches you’ll want to update your state after the response is received instead of returning it (wrapped in a promise).
axios.get('api.php')
.then(result => {
console.log(result.data);
this.setState({ data: result.data });
});
A typical pattern for fetching data is to do it in the componentDidMount
lifecycle function (in the case of class-based components) or an useEffect
hook with empty dependency array (for functional components).
class Demo extends Component {
state = {
data: {},
};
componentDidMount() {
axios.get('api.php')
.then(result => {
console.log(result.data);
this.setState({ data: result.data });
});
}
}
or
const Demo = () => {
const [data, setData] = useState({});
useEffect(() => {
axios.get('api.php')
.then(result => {
console.log(result.data);
setData(result.data);
});
}, []);
};