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!
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
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.