0

So I want to have fetch request in separate file. Just for testing. And then call it in componentDidMount. I still get undefined. What is the proper way of doing it?

This is my function:

    const fetchNewWord = () => {
  fetch("https://wordsapiv1.p.rapidapi.com/words/?lettersMax=11&random=true", {
    headers: {
      "X-Rapidapi-Host": "wordsapiv1.p.rapidapi.com",
      "X-Rapidapi-Key": "myKey"
    }
  })
    .then(data => data.json())
    .then(data => {
      return data.word;
    });
};

export default fetchNewWord;
kenodek
  • 362
  • 1
  • 2
  • 13

2 Answers2

2

You have return your fetch callback results as function's response:

export const fetchNewWord = () => {
  return fetch("https://wordsapiv1.p.rapidapi.com/words/?lettersMax=11&random=true", {
    headers: {
      "X-Rapidapi-Host": "wordsapiv1.p.rapidapi.com",
      "X-Rapidapi-Key": "myKey"
    }
  })
  .then(data => data.json())
  .then(data => data.word);
};

When you do const data = fetchNewWord(); console.log(data);, you'll see the result.

Avanthika
  • 3,984
  • 1
  • 12
  • 19
0

You can create a separate service for fetch in your code and use it as a independent providers

Here is the httpRequest.js which you can use default fetch api:

import axios from 'axios';

class HttpRequest {
  constructor(baseURL) {
    this.axios = axios.create({
      baseURL,
    });
  }

  reponseInterceptor() {
    // Add a response interceptor
    this.axios.interceptors.response.use(
      response => (
        // Do something with response data
        response
      ),
      error => (
        // Do something with response error
        Promise.reject(error)
      ),
    );
  }

  requsetInterceptor() {
    this.axios.interceptors.request.use(
      config => (
        // Do something before request is sent
        config),
      error => (
        // Do something with request error
        Promise.reject(error)
      ),
    );
  }

  fetch(url, params, config = {}) {
    return this.axios.get(url, {
      params,
      ...config,
    });
  }

  create(url, data, config = {}) {
    return this.axios.post(url, data, {
      ...config,
    });
  }

  update(url, data, config = {}) {
    return this.axios.put(url, data, {
      ...config,
    });
  }

  patch(url, data, config = {}) {
    return this.axios.patch(url, data, {
      ...config,
    });
  }

  remove(url, params, config = {}) {
    return this.axios.delete(url, {
      params,
      ...config,
    });
  }
}

export default HttpRequest;

Here is how you can create your words.js services:

import config from 'config';
import HttpRequest from './httpRequest';

export default class WordService extends HttpRequest {
  constructor(servicePath) {
    super(config.markMeHost);
    this.path = `${config.markMeHost}/${servicePath}`;
  }

  listWords() {
    return this.fetch(this.path, {});
  }

  createWords(data) {
    return this.create(this.path, data);
  }

  updateWords(data, id) {
    return this.update(`${this.path}/${id}`, data);
  }

  deleteWords(id) {
    return this.remove(`${this.path}/${id}`);
  }
}

Your api service index.js:

import WordService from './words';

// Give arg to provider to start endpoint with specific path for example = abc.com/api/words
export default new WordService('words');

For further details you can check my github account for axios service https://github.com/m-nathani/markme/tree/master/frontend/src/service/api

Murtaza Hussain
  • 3,851
  • 24
  • 30