Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

javascript - Try to display data using Mobx from API

Im making React app that shows coins' data from API. I did it with useEffect and it works fine, but now I'm trying to do the same using Mobx. Im trying to create a store file that gets the data from an API and stores it, then passes it to App.js and then displays the data on screen.

Im new with Mobx. Please help me resolving my Issue

This is my useEffect:

useEffect(() => {
    axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false')
      .then(res => {
        setCoins(res.data)
        console.log(res.data)
      }).catch(error => console.log(error))
  }, []);

How can I convert this useEffect to Mobx in Store.js file? For the first step I just want to display coins' name.

Thanks!

question from:https://stackoverflow.com/questions/65946495/try-to-display-data-using-mobx-from-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The structure should look like this one:

// Coins Store file
type Coin = {
  name: string;
}

export class CointStore {
  // not sure what is your coins data type, lets assume this is array 
  readonly coins = observable<Coin>([]);

  constructor() {
    makeAutoObservable(this);
  }

  getCoins() {
    return axios.get('https://api.coingecko.com/api/v3/coins/markets')
       .then(response => this.coins.replace(response.data);
  }
}

...

// this is app.js file

import {observer} from 'mobx-react-lite'
import {createContext, useContext, useEffect} from "react"
import {CointStore} from './CointStore'

const CoinsContext = createContext<CointStore>()

const CoinsView = observer(() => {
  const coinStore = useContext(CoinsContext);

  useEffect(() => {
    coinStore.getCoins()
  }, []);

  return (
    <span>
      {coinStore.coins.map(coin => <span>{coin.name}</span>)}
    </span>
  )
})

ReactDOM.render(
  <CoinsContext.Provider value={new CointStore()}>
    <CoinsView />
  </CoinsContext.Provider>,
  document.body
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...