1

I have this Unstated container:

import { Container } from 'unstated';
import axios from 'axios';

export default class CurrenciesContainer extends Container {
  state = { currencies: null };
  async fetch() {
    const { data: currencies } = await axios.get('http://localhost:8080/get-currencies');
    this.setState({ currencies });
  }
}

And this function that utilises it:

static renderCurrencies() {
  return (
    <Subscribe to={[CurrenciesContainer]}>
      {(currencies) => {
        if (!currencies.state.currencies) {
          currencies.fetch();
        }
        return <small>Currencies: {currencies.state.currencies}</small>;
      }}
    </Subscribe>
  );
}

I wanted to try and destructure the params coming into the <Subscribe> like so:

static renderCurrencies() {
  return (
    <Subscribe to={[CurrenciesContainer]}>
      {({ state, fetch }) => {
        if (!state.currencies) {
          fetch();
        }
        return <small>Currencies: {state.currencies}</small>;
      }}
    </Subscribe>
  );
}

But this breaks with Uncaught (in promise) TypeError: this.setState is not a function

Clearly it's not binding properly but I'm not sure why the destructuring of the function would change its binding. Anyone able to offer an explanation/way of doing it like this? Thanks!

Matt Fletcher
  • 8,182
  • 8
  • 41
  • 60

1 Answers1

2

Replace async fetch() {} with fetch = async () => {} to achieve the correct binding.

Try this in your Unstated container:

import { Container } from 'unstated';
import axios from 'axios';

export default class CurrenciesContainer extends Container {
  state = { currencies: null };
  fetch = async () => {
    const { data: currencies } = await axios.get('http://localhost:8080/get-currencies');
    this.setState({ currencies });
 }
}
Matt Fletcher
  • 8,182
  • 8
  • 41
  • 60
Guruprasad
  • 753
  • 6
  • 23
  • 1
    Yeah you're right, `fetch = async () => {` does the trick (although I'm not sure why you modified the code inside the function...?) Thanks – Matt Fletcher Aug 29 '19 at 10:57
  • as both the codes does same thing , but your code looks much cleaner, thanks for the edit – Guruprasad Aug 29 '19 at 11:37