I'm trying to parse a json received from external api.
My reducer is:
import { RECEIVED_FORECAST } from '../actions/index';
export default function ForecastReducer (state = [], action) {
switch (action.type) {
case RECEIVED_FORECAST:
return Object.assign({}, state, {
item: action.forecast
})
default:
return state;
}
}
Then main reducer goes like:
import { combineReducers } from 'redux';
import ForecastReducer from './forecast_reducer';
const rootReducer = combineReducers({
forecast: ForecastReducer
});
export default rootReducer;
and container looks like
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
class WeatherResult extends Component {
render() {
const forecast = this.props.forecast.item;
{console.log('almost: ', forecast)}
return (
<div>
<h1> </h1>
</div>
)
}
}
function mapStateToProps({ forecast }) {
return {
forecast
}
}
export default connect(mapStateToProps)(WeatherResult)
Output of the almost is exactly the same son as I supposed:
almost:
Object
currently: {time: 1476406181, summary: "Drizzle", icon: "rain", nearestStormDistance: 0, precipIntensity: 0.0048, …}
daily: {summary: "Light rain on Saturday and Thursday, with temperatures rising to 92°F on Wednesday.", icon: "rain", data: Array}
So, my question is, how can I show the value of, let's say forecast.currently.summary?
1) If I just try to insert it within {} I receive : 'TypeError: undefined is not an object (evaluating 'forecast.currently')'
2) I can't use mapping as the json might have other components added
Is there any method to get to this property directly, without mapping all the file?
Thanks
The problem you have is that you're requesting the data. That doesn't complete immediately. Think about what the app is doing while you're waiting for the weather data to arrive.
It's displaying something. In your case, the render method is failing because you're trying to show data that hasn't arrived yet.
The solution:
render() {
const forecast = this.props.forecast;
const text = forecast && forecast.item.currently.summary || 'loading...';
return (
<div>
<h1>{text}</h1>
</div>
)
}
}
This way you check if you already have the data and if not, you show something useful.
Related
I am trying out a small sample in nextjs. All that the proj does is to fetch json data from a file and try displaying it in list of a component. But the behavior is weird. Its getting into infinite loop and I have no clue what's wrong. Could some one take a look at https://github.com/SamplesForMurthy/sampleCode and help me figure out what the issue is? Not able to fetch the data nor I am able to display.
I cloned and fixed. You don't need to use fs.readFileSync here, or fs at all for that matter. You can simply import the .json file as an arbitrarily named variable then map it out.
Here is how I got the data rendering:
import React from 'react';
import testData from '../TestData/SampleData.json';
import SampleParentComponent from '../components/SampleParentComponent';
function TestPage({ filecontent }) {
console.log(`filecontent: ${filecontent}`);
return (
<div>
<SampleParentComponent data={filecontent}></SampleParentComponent>
</div>
);
}
export const getStaticProps = async ctx => {
console.log(ctx.query);
const filecontent = await testData;
return {
props: { filecontent }
};
};
export default TestPage;
/**
* (property) filecontent: {
data: {
seqNo: number;
contactName: string;
}[];
}
*/
I'm learning React and a little about API's. I'm using the Destiny 2 API as a starting API to try to wrap my head around how they work.
Here is my Api.js file:
import React, { Component } from 'react';
import './style.css';
import axios from 'axios';
class Api extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
}
componentDidMount() {
let config = {
headers: {
'X-API-KEY': 'key-here',
},
};
axios
.get('https://www.bungie.net/Platform/Destiny2/4/Profile/4611686018484544046/?components=100', config)
.then((response) => {
console.log(response);
this.setState({
data: response.data,
});
});
}
render() {
const { item } = this.state;
return (
<div>
{Array.isArray(item) &&
item.map((object) => <p key={object.data}>{object.data.Response.profile.data.userInfo.displayName}</p>)}
</div>
);
}
}
export default Api;
The data from the API is returned as an object that contains a nested array. I can get the data to display in the console no problem.
This is the layout of the response object output to the console:
I'm trying to grab the value of "displayName" and output it into the DOM, what am I doing wrong?
I have tried returning the data as JSON by doing:
response => {return(data.json())} and iterating through the json object using {Object.keys(this.state.data).map((key) => but I have still managed to only get data in the console and not in the DOM.
Is there anything that seems to be missing? I've been stuck with this problem for several days now!
EDIT: This is the whole response from the API call
{
"Response": {
"profile": {
"data": {
"userInfo": {
"membershipType": 4,
"membershipId": "4611686018484544046",
"displayName": "Snizzy"
},
"dateLastPlayed": "2019-04-05T14:28:30Z",
"versionsOwned": 31,
"characterIds": [
"2305843009409505097",
"2305843009411764917",
"2305843009425764024"
]
},
"privacy": 1
}
},
"ErrorCode": 1,
"ThrottleSeconds": 0,
"ErrorStatus": "Success",
"Message": "Ok",
"MessageData": {}
}
In the render function, where you destructure you state, you have the wrong property.
const { item } = this.state; should be const { data } = this.state;
More about destructuring here.
Also, you need to make changes here:
EDIT: Actually, your data isn't even an array. You don't have to iterate through it.
<div>
<p>{data.Response.profile.data.userInfo.displayName}</p>}
</div>
Let's do a check to make sure that we got back the api before running. You might be rendering before the api call is finished. Try using an inline statement.
{ item ? {Array.isArray(item) && item.map(object => (
<p key={object.data}>{object.data.Response.profile.data.userInfo.displayName}</p>
))}
:
<div>Loading...</div>
I am creating a Spotify app with its API. I want 4 views (like '/', 'nowPlaying', 'favouriteArtists', 'favouriteSongs').
I need to setAccessToken for using functions like getMyCurrentPlaybackState() in every new page, right?. Idk if I need to if(params.access_token){spotifyWebApi.setAccessToken(params.access_token)} in every container that will use functions like getMyCurrentPlaybackState(). I was thinking of creating a Spotify.jsx container that handle the store of the Spotify Object (which is used in the token and in every container that use spotify functions). But with this Spotify.jsx i don't know either if it is a good approach nor how to connect its needed spotifyWebApi const to every container file and token file.
For better understanding of my idea: I would create a Token.jsx that has getHashParams() and a Playing.jsx that has getNowPlaying(). Every one needs the spotifyWebApi const.
import React, { Component } from 'react';
import Spotify from 'spotify-web-api-js';
const spotifyWebApi = new Spotify();
class App extends Component {
constructor(){
super();
const params = this.getHashParams();
this.state = {
loggedIn: params.access_token ? true : false,
nowPlaying: {
name: 'Not Checked',
image: ''
}
}
if (params.access_token){
spotifyWebApi.setAccessToken(params.access_token)
}
}
getHashParams() {
var hashParams = {};
var e, r = /([^&;=]+)=?([^&;]*)/g,
q = window.location.hash.substring(1);
while ( e = r.exec(q)) {
hashParams[e[1]] = decodeURIComponent(e[2]);
}
return hashParams;
}
getNowPlaying(){
spotifyWebApi.getMyCurrentPlaybackState()
.then((response) => {
this.setState({
nowPlaying: {
name: response.item.name,
image: response.item.album.images[0].url
}
})
})
}
}
Your title mentions Redux, but I don't see your code utilizing it. With Redux, you could get the access_token and then store it in state. This will allow you to use it in any Redux connected component.
Also, with Redux, you can use Redux Thunk (or similar) middleware that will allow you to use Redux actions to call an API. So then you would just write the different API calls as Redux actions, which would allow you to call them from any component, and have the results added to your Redux store (which again, can be used in any Redux connected component).
So, for example, your getNowPlaying() function could be an action looking something like this:
function getNowPlaying() {
return function (dispatch, getState) {
// get the token and init the api
const access_token = getState().spotify.access_token
spotifyWebApi.setAccessToken(access_token)
return spotifyWebApi.getMyCurrentPlaybackState().then((response) => {
dispatch({
type: 'SET_NOW_PLAYING',
name: response.item.name,
image: response.item.album.images[0].url
})
})
}
}
Note: You'll need to configure the Redux reducer for "spotify" (or however you want to structure your store) to store the data you need.
So, you could then call getNowPlaying() from any component. It stores the results in the redux store, which you could also use from any connected component. And you can use the same technique of getting the access_token from the store when needed in the actions.
Alternatively, if you didn't want to use Redux, you could provide context values to all child components, using React's Context features. You could do this with that token that each component would need in your setup. But Redux, in my opinion, is the better option for you here.
Instead of passing this const to other components, I would create a SpotifyUtils.jsx and inside it declare the const. And in this helper file I would export functions so other components can use them.
For example:
import Spotify from 'spotify-web-api-js';
const spotifyWebApi = new Spotify();
let token = null
export function isLoggedIn() {
return !!token
}
export function setAccessToke(_token) {
token = _token;
spotifyWebApi.setAccessToken(_token);
}
export function getNowPlaying(){
return spotifyWebApi.getMyCurrentPlaybackState()
.then((response) => {
return {
name: response.item.name,
image: response.item.album.images[0].url
}
})
}
So that in the components you can use them like so:
import React, { Component } from 'react';
import {
isLoggedIn,
setAccessToken,
getNowPlaying,
} from 'helpers/SpotifyUtils'
class App extends Component {
constructor(){
super();
this.state = {
loggedIn: isLoggedIn(),
nowPlaying: {
name: 'Not Checked',
image: ''
}
}
getHashParams() {
var hashParams = {};
var e, r = /([^&;=]+)=?([^&;]*)/g,
q = window.location.hash.substring(1);
while ( e = r.exec(q)) {
hashParams[e[1]] = decodeURIComponent(e[2]);
}
return hashParams;
}
componentDidMount() {
if (!this.state.loggedIn) {
const params = this.getHashParams();
if (params.access_token) {
setAccessToken(params.access_token)
getNowPlaying()
.then(nowPlaying => this.setState({ nowPlaying }))
}
}
}
}
This will enable your spotifyWebApi const to be reused in any component you import the helper functions. I am particularly found of this pattern, creating utils or helpers in a generic fashion so that you can reuse code easily. Also if spotify Web Api releases a breaking change, your refactor will be easier because you will only need to refactor the SpotifyUtils.jsx file since it will be the only file using import Spotify from 'spotify-web-api-js'
I have a React Native app on which I'm trying to apply Redux. It's the first time I try to use Redux, so I think I'm not seeing the elephant in the room.
The problem is that I can't access my props data (generated with mapStateToProps). Here's my code:
reducer.js (in the console log I see the json objects just fine)
const INITIAL_STATE = {
etiquetas: []
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case FETCH_ETIQUETAS_SUCCESS:
//console.log("payload: "+action.payload);
return { ...state, etiquetas: action.payload };
default:
return state;
}
};
component.js (in the console.log I see my data, BUT it seems that it's all in one object now, this is probably what I'm not seeing).
class EtiquetasList extends Component {
componentDidMount() {
this.props.FetchEtiquetas();
}
renderEtiquetas() {
//console.log("etq: "+JSON.stringify(this.props.etiquetas));
if ( this.props.etiquetas.length == 0 ) {
return <ActivityIndicator size="large" color="#00ff00" />
} else {
return this.props.map(etiqueta =>
<EtiquetaDetail key={etiqueta.id} etiqueta={etiqueta} />
);
}
}
render() {
return (
<ScrollView>
{this.renderEtiquetas()}
</ScrollView>
);
}
}
const mapStateToProps = (state) => {
return {
etiquetas: state.etiquetas
};
};
export default connect(mapStateToProps, { FetchEtiquetas })(EtiquetasList);
The map function is for Arrays, not Objects, I know. That's part of my old code.
action.js
import axios from 'axios';
import { FETCH_ETIQUETAS, FETCH_ETIQUETAS_SUCCESS, FETCH_ETIQUETAS_FAILURE } from './types';
const url= 'https://e.dgyd.com.ar/wp-json/wp/v2/etiquetas?_embed&per_page=7';
const fetchSuccess = (dispatch, data)=> {
dispatch({
type: FETCH_ETIQUETAS_SUCCESS,
payload: data
});
}
export function FetchEtiquetas() {
return function (dispatch) {
axios.get( url )
.then(response => {
dispatch({ type: FETCH_ETIQUETAS_SUCCESS, payload: response.data })
} );
}
}
reducers/index.js
import { combineReducers } from 'redux';
import DataReducer from './DataReducer';
export default combineReducers({
etiquetas: DataReducer
});
So, my questions are:
Why is is this always returning undefined?
this.props.etiquetas.length == 0
Why mapStateToProps seems to convert my array of objects into a single object? is this why I have to use JSON.stringify in the console log?
and finally, how do I access my data in the component?
Thank you much in advance!
The problem here, is just the way that you structured your reducer.
const INITIAL_STATE = {
etiquetas: []
};
The code above means that you are creating an object, with a property named "etiquetas" that holds an empty array initially.
In your root reducer file, you import that object, and assign it the name, "etiquetas". So really what your reducer is returning is this:
etiquetas: {
etiquetas: [your array of data]
}
This would explain why you complained about receiving an object. There are two ways to rectify this,
One: Change the mapStateToProps function to this,
const mapStateToProps = (state) => {
return {
etiquetas: state.etiquetas.etiquetas
};
};
Two: Change your reducer to look like this,
export default (state = [], action) => {
switch (action.type) {
case FETCH_ETIQUETAS_SUCCESS:
//console.log("payload: "+action.payload);
return action.payload;
default:
return state;
}
};
This will make sure your reducer returns just an array, not an object with an array inside of it stored in a property. Its up to you to decide which you like better.
I have some URL with json and need to read data.
For the sake of this example json looks like this:
{
"results": [
...
],
"info": {
...
}
}
I want to return fetched data as a property of a component.
What is the best way to do it?
I tried to do that with axios. I managed to fetch data, but after setState in render() method I received an empty object. This is the code:
export default class MainPage extends React.Component {
constructor(props: any) {
super(props);
this.state = {
list: {},
};
}
public componentWillMount() {
axios.get(someURL)
.then( (response) => {
this.setState({list: response.data});
})
.catch( (error) => {
console.log("FAILED", error);
});
}
public render(): JSX.Element {
const {list}: any = this.state;
const data: IScheduler = list;
console.log(data); // empty state object
return (
<div className="main-page-container">
<MyTable data={data}/> // cannot return data
</div>
);
}
}
I don't have a clue why in render() method the data has gone. If I put
console.log(response.data);
in .then section, I get the data with status 200.
So I ask now if there is the other way to do that.
I would be grateful for any help.
----Updated----
In MyTable component I got an error after this:
const flightIndex: number
= data.results.findIndex((f) => f.name === result);
Error is:
Uncaught TypeError: Cannot read property 'findIndex' of undefined
What's wrong here? How to tell react this is not a property?
Before the request is returned, React will try to render your component. Then once the request is completed and the data is returned, react will re-render your component following the setState call.
The problem is that your code does not account for an empty/undefined data object. Just add a check, i.e.
if (data && data.results) {
data.results.findIndex(...);
} else {
// display some loading message
}
In React, after you have stored your ajax result in the state of the component (which you do appear to be doing), you can retrieve that result by calling this.state.list
So to make sure this is working properly, try <MyTable data={this.state.list}>
https://daveceddia.com/ajax-requests-in-react/