Amit Erandole Amit Erandole - 6 months ago 10
Ajax Question

React: How do I move my ajax api call into a separate component?

Here is a typical container component that is working perfectly well:

const API = 'https://randomuser.me/api/?results=5';
class App extends Component {

constructor(props) {
super(props);
this.state = { profiles: [] };
}

componentDidMount() {
this.fetchProfiles();
}

fetchProfiles() {
let url = API;
fetch(url)
.then( (res) => res.json() )
.then( (data) => {
let results = data.results;
this.setState({
profiles: results
});
})
.catch( (error) => console.log('Oops! . There Is A Problem', error) );
}

render() {
// rendering child component here
}
}

export default App;


What I am trying to do now is move the
fetchProfiles
function into a separate api component.

So I make a
profiles.js
file in an
api
folder in my project:

const API = 'https://randomuser.me/api/?results=5';

export function fetchProfiles() {
let url = API;
fetch(url)
.then( (res) => res.json() );
}


And now my main component imports it and uses it like so:

import { fetchProfiles } from '../api/profiles.js';


const API = 'https://randomuser.me/api/?results=5';
class App extends Component {

constructor(props) {
super(props);
this.state = { profiles: [] };
}

componentDidMount() {
fetchProfiles.then((data) => {
let results = data.results;
this.setState({
profiles: results
});
});
}

// render call etc


But when I run the call in
componentDidMount
like this, I get this error:
Uncaught TypeError: _profiles.fetchProfiles.then is not a function
. I am trying to chain with
then
because the fetch api returns
res.json()
as a promise.

I tried wrapping
fetchProfiles
in a outer function, in a new promise too! But nothing works!! What am I doing wrong here? Please help with this refactoring.

Answer

You need to return fetch(url) itself, so you'll return a promise and then you can use then method:

const API = 'https://randomuser.me/api/?results=5';

export function fetchProfiles() {
  let url = API;

  // return the promise itself
  return fetch(url).then( (res) => res.json() );
}
Comments