setting state inside react context with axios response

时间:2018-09-29 16:25:12

标签: reactjs react-redux axios

I have an http get request which returns json. I want to store that response in a state variable. This is in context.js:

switch(action.type) {
        case 'BUSCAR_LIBRO':
            return {
                ...state,
                respuestaJson: axios.get('https://www.googleapis.com/books/v1/volumes?q=' + action.payload.split(' ').join('+'))
                .then(response => {})
            }
        default:
            return state;
    }

The value of respuestaJson that I get is promise{}

3 个答案:

答案 0 :(得分:0)

您现在可能已经将所有内容包装到setState中。

someMethod = () => {
  this.setState(state => {
    ...YOUR CURRENT CODE
  })
}

您需要在更新后调用api

someMethod = () => {
 switch (action.type) {
  case 'BUSCAR_LIBRO':
    axios.get('https://www.googleapis.com/books/v1/volumes?q=' + action.payload.split(' ').join('+'))
    .then(res => {this.setState(...UPDATE)});
  default:
    return null;
 }
}

答案 1 :(得分:0)

好吧,由于我们没有很多代码,所以我只能猜测哪些对您有用。但是,这是异步操作的完成方式:

import React, { PureComponent, createContext } from 'react';
import axios from 'axios';

const getDefaultContext = () => ({
  books: null,
  fetchBooks: () => {},
})

const Context = createContext(getDefaultContext());

class BookProvider extends PureComponent {
  constructor(props) {
    super(props);

   this.fetchBooks = this.fetchBooks.bind(this);

    this.state = {
      books: null,
      fetchBooks: this.fetchBooks,
    };
  }

  fetchBooks() {
    axios
      .get('http://something')
      .then(response => {
        this.setState(prevState => { ...prevState, books: response.books });
      });
  }

  render() {
    const { children } = this.props;

    return (
      <Context.Provider context={this.state}>
        {children}
      </Context.Provider>
    );
  }
}

然后,在您的一些孩子中:

<Context.Consumer>
  {context => <Button onClick={context.fetchBooks}>Load books</Button>}
</Context.Consumer>

但是您的代码确实看起来不像您正在使用上下文API ...

答案 2 :(得分:0)

首先,您需要将上下文分配给变量。

yourFunction = () => {
  let self = this;
  switch(action.type) {
        case 'BUSCAR_LIBRO':
            return {
                ...state,
                respuestaJson: axios.get('https://www.googleapis.com/books/v1/volumes?q=' + action.payload.split(' ').join('+'))
                .then(response => {
                 self.foo = response.data;
                 })
            }
        default:
            return state;
    }

}