Reputation: 673
So I`m trying to create a service to be used in the entire project which makes an API call to retrieve some data from the server. The function looks something like this
export function data(){
const proxyurl = "https://cors-anywhere.herokuapp.com/";
fetch(proxyurl+process.env.REACT_APP_TEXT_API)
.then(res => res.json())
.then(json => {
return json;
})
}
I`m trying to access the returned json in my React component by doing this
import {data} from '../../../../services/textService/textApi'
class Error404Page extends React.Component {
constructor(props) {
super(props);
this.state = {
data: "Something"
}
}
componentDidMount() {
this.setState({
data: this.data()
})
}
The problem is the state variable "data" value is set to undefined. How can I access the data returned by my function?
Upvotes: 1
Views: 67
Reputation: 5852
JavaScript functions that are expected to return something must explicitly return them. Here's an example of the original post's code that returns the promise. I've thrown the function call into a Hook, but the same thing could be accomplished in a class-based component.
import React, {useEffect} from "react";
import ReactDOM from "react-dom";
function data(){
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then(json => json)
}
function App() {
useEffect(() => {
data().then(resp => console.log(resp))
})
return (
<div />
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
This will log the response of our sample API endpoint to the console when App
mounts.
Returning Promise Demo (Code Sandbox)
Upvotes: 1
Reputation: 31565
You forgot to return the fetch
.
export function data(){
const proxyurl = "https://cors-anywhere.herokuapp.com/";
// added return statement
return fetch(proxyurl+process.env.REACT_APP_TEXT_API)
.then(res => res.json())
.then(json => {
return json;
})
}
But this will also have some problems, you need to use await/async
or .then
.
async componentDidMount() {
// using await / async
const newData = await data()
this.setState({
data: newData
})
}
If you want to call data
that comes from import {data} from '...'
, you don't use this.data()
. this
will be from your component, not from the import.
Upvotes: 0