I have this code in react app:
function xyz (callback) {
axios.get(`https://example.com`)
.then(res => {
const filepath = res.data.Items[0].filepath.S
callback ({autoplay: false, controls: true,sources: [{src: filepath}]})
}).catch(err =>{
console.log(err);
})
}
function App() {
return (
<VideoPlayer { ...xyz(function(response) {console.log(response)});} />
)
}
This works as expected and I can log the response. But what I am trying to do is assign the response of the xyz function directly within the VideoPlayer tags.
For e.g., What I want to achieve is:
<VideoPlayer {...return-value-of-xyz-function}
How do I achieve this? Happy to provide more context if needed. Thanks!
CodePudding user response:
Render functions are always synchronous. Because your xyz function is asynchronous, you have to deal with all of the intermediary state: loading, error, no data, etc.
I recommend creating a hook for this type of stuff, that way you can establish a pattern and reuse around your app. Or you can take the code from the hook and put it directly in your App function - it's up to you.
const useFetchData = (url) => {
const [state, setState] = useState({ isLoading: true, error: null, data: null });
useEffect(() => {
axios.get(url)
.then((res) => {
setState({ isLoading: false, data: res.data, error: null });
})
.catch((error) => {
setState({ isLoading: false, data: null, error });
});
}, [url]);
return state;
};
const App = () => {
const { isLoading, data, error } = useFetchData("https://example.com");
if (isLoading) return <div>Loading...</div>;
if (error) return <div>There was an error: {error}</div>;
return <VideoPlayer {...data} />;
};
