Reputation: 39
I'm trying to get access to the store from outside of the component and subscribe it for store changes. I have separate file which I'm using to make an API call.
import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import store from '../store/store'
const currentWeatherApi = {
key: "",
base: "https://api.openweathermap.org/data/2.5/"
}
const API = () => {
const inputValue = useSelector(state => state.inputValue);
store.subscribe(() => {
console.log(inputValue)
})
if(inputValue) {
fetch(`${currentWeatherApi.base}weather?q=rzeszow&units=metric&APPID=${currentWeatherApi.key}`)
.then(res => res.json())
.then(result => {
const temp = (Math.floor(result.main.temp));
const tempMin = result.main.temp_min
const tempMax = result.main.temp_max;
const location = result.name;
const sunrise = new Date(result.sys.sunrise * 1000).toISOString().substr(11, 8);
const sunset = new Date(result.sys.sunset * 1000).toISOString().substr(11, 8);
const country = result.sys.country;
const wind = result.wind.speed;
const pressure = result.main.pressure;
const sky = result.weather[0].main;
})
}
export default API;
When I try to console.log anything, nothing happens, like it's not even read. What am I doing wrong?
Upvotes: 0
Views: 4826
Reputation: 203457
API
isn't a React component so the useSelector
hook won't work. You can import the store and call getState on it to get the current state's value.
getState()
Returns the current state tree of your application. It is equal to the last value returned by the store's reducer.
Returns
(any): The current state tree of your application.
const API = () => {
const state = store.getState();
if(state.searchingBar.inputValue) {
fetch(`${currentWeatherApi.base}weather?q=rzeszow&units=metric&APPID=${currentWeatherApi.key}`)
.then(res => res.json())
.then(result => {
....
})
}
}
Demo code:
const initialState = {
inputValue: ""
};
const slice = createSlice({
initialState,
name: "searchingBar",
reducers: {
updateValue: (state, action) => {
state.inputValue = action.payload;
}
}
});
const rootReducer = combineReducers({
searchingBar: slice.reducer
});
const store = configureStore({
reducer: rootReducer
});
const fetch = (url, options) => {
console.log("fetch", { url });
return new Promise((resolve) => {
const response = {
json: async () => "boom"
};
return resolve(response);
});
};
const currentWeatherApi = {
base: "base",
key: "key"
};
const API = () => {
const state = store.getState();
console.log(JSON.stringify(state));
if (state.searchingBar.inputValue) {
fetch(
`${currentWeatherApi.base}weather?q=rzeszow&units=metric&APPID=${currentWeatherApi.key}`
)
.then((res) => res.json())
.then((result) => {
console.log("Result", result);
store.dispatch(slice.actions.updateValue(""));
});
}
};
export default function App() {
return (
<Provider store={store}>
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button type="button" onClick={API}>
Call API
</button>
<button
type="button"
onClick={() => store.dispatch(slice.actions.updateValue("test"))}
>
Update State
</button>
</div>
</Provider>
);
}
Upvotes: 4