I am trying to populate a dropdown with values from API. I declared empty array in react class but cannot assign the values to it. I cannot use it as state variables as I have to make lot of changes to previously developed code. The way I did the code it says options is not defined.
The partial code is posted below which is causing the problem. Any help is really appreciated.
export default class LoadLimits extends Component {
constructor(props){
super(props);
this.options = []
this.getZoneOptions = this.getZoneOptions.bind(this)
}
render(){
return (
<PtSelect label="Assigned Zone" options={options}
onChange={this.onChangeDropdown}
disabled={this.props.disabled}
defaultVal={this.state.assignedZone} name="assignedZone" />
)
}
getZoneOptions = () =>{
const zoneOptions = []
const keys = []
fetch(`${config.server}/getzoneOptions/`+this.props.ownModel.agencyId)
.then(response=>
{
return response.json();
})
.then(data=>{
for (var i =0;i<data[0].length;i++){
if (data[0][i]['Zone_key']!==998){
zoneOptions.push(data[0][i]['description'])
keys.push(data[0][i]['Zone_key'])
}
}
let dropOptions = zoneOptions.map((option,idx)=>{
return {key:keys[idx],value: option, label:option}
});
this.options = dropOptions
})
.catch(error=>{
console.log(error);
});
}
}
Issue
The options being passed to PtSelect is not defined.
<PtSelect
label="Assigned Zone"
options={options} // <-- should be this.options
onChange={this.onChangeDropdown}
disabled={this.props.disabled}
defaultVal={this.state.assignedZone}
name="assignedZone"
/>
Solution
If you need a variable to hold a value that you don't want coupled to the React component lifecycle then you should probably use a React ref.
Import createRef from 'react'.
Create a mutable ref for the options.
Implement the componentDidMount lifecycle method to populate and set the current value of the options.
Pass the current options value to the PtSelect component.
Code
import React, { Component, createRef } from 'react';
class LoadLimits extends Component {
constructor(props) {
super(props);
this.getZoneOptions = this.getZoneOptions.bind(this);
this.options = createRef([]);
}
getZoneOptions = () => {
const zoneOptions = [];
const keys = [];
fetch(`${config.server}/getzoneOptions/` + this.props.ownModel.agencyId)
.then((response) => {
return response.json();
})
.then((data) => {
for (var i = 0; i < data[0].length; i++) {
if (data[0][i]["Zone_key"] !== 998) {
zoneOptions.push(data[0][i]["description"]);
keys.push(data[0][i]["Zone_key"]);
}
}
const dropOptions = zoneOptions.map((option, idx) => {
return { key: keys[idx], value: option, label: option };
});
this.options.current = dropOptions;
})
.catch((error) => {
console.log(error);
});
};
componentDidMount() {
this.getZoneOptions();
}
render() {
return (
<PtSelect
label="Assigned Zone"
options={this.options.current}
onChange={this.onChangeDropdown}
disabled={this.props.disabled}
defaultVal={this.state.assignedZone}
name="assignedZone"
/>
);
}
}
Alternative Solution - Use forceUpdate (not strongly suggested)
In addition to addressing the this.options issue in PtSelect, you can use forceUpdate to tell React to rerender regardless of any state and/or prop update. This should rerender the select with populated options.
component.forceUpdate(callback)
By default, when your component’s state or props change, your
component will re-render. If your render() method depends on some
other data, you can tell React that the component needs re-rendering
by calling forceUpdate().
Calling forceUpdate() will cause render() to be called on the
component, skipping shouldComponentUpdate(). This will trigger the
normal lifecycle methods for child components, including the
shouldComponentUpdate() method of each child. React will still only
update the DOM if the markup changes.
Normally you should try to avoid all uses of forceUpdate() and only
read from this.props and this.state in render().
getZoneOptions = () => {
const zoneOptions = [];
const keys = [];
fetch(`https://jsonplaceholder.typicode.com/users`)
.then((response) => {
return response.json();
})
.then((data) => {
for (var i = 0; i < data.length; i++) {
zoneOptions.push(data[i]["name"]);
keys.push(data[i]["id"]);
}
let dropOptions = zoneOptions.map((option, idx) => {
return { key: keys[idx], value: option, label: option };
});
this.options = dropOptions;
console.log("Options ", this.options);
this.forceUpdate(); // <-- trigger a rerender
})
.catch((error) => {
console.log(error);
});
};
Related
I'm currently fetching data in Component1, then dispatching an action to update the store with the response. The data can be seen in Component2 in this.props, but how can I render it when the response is returned? I need a way to reload the component when the data comes back.
Initially I had a series of functions run in componentDidMount but those are all executed before the data is returned to the Redux store from Component1. Is there some sort of async/await style between components?
class Component1 extends React.Component {
componentDidMount() {
this.retrieveData()
}
retrieveData = async () => {
let res = await axios.get('url')
updateParam(res.data) // Redux action creator
}
}
class Component2 extends React.Component {
componentDidMount() {
this.sortData()
}
sortData = props => {
const { param } = this.props
let result = param.sort((a,b) => a - b)
}
}
mapStateToProps = state => {
return { param: state.param }
}
connect(mapStateToProps)(Component2)
In Component2, this.props is undefined initially because the data has not yet returned. By the time it is returned, the component will not rerender despite this.props being populated with data.
Assuming updateParam action creator is correctly wrapped in call to dispatch in mapDispatchToProps in the connect HOC AND properly accessed from props in Component1, then I suggest checking/comparing props with previous props in componentDidUpdate and calling sortData if specifically the param prop value updated.
class Component2 extends React.Component {
componentDidMount() {
this.sortData()
}
componentDidUpdate(prevProps) {
const { param } = this.props;
if (prevProps.param !== param) { // <-- if param prop updated, sort
this.sortData();
}
}
sortData = () => {
const { param } = this.props
let result = param.sort((a, b) => a - b));
// do something with result
}
}
mapStateToProps = state => ({
param: state.param,
});
connect(mapStateToProps)(Component2);
EDIT
Given component code from repository
let appointmentDates: object = {};
class Appointments extends React.Component<ApptProps> {
componentDidUpdate(prevProps: any) {
if (prevProps.apptList !== this.props.apptList) {
appointmentDates = {};
this.setAppointmentDates();
this.sortAppointmentsByDate();
this.forceUpdate();
}
}
setAppointmentDates = () => {
const { date } = this.props;
for (let i = 0; i < 5; i++) {
const d = new Date(
new Date(date).setDate(new Date(date).getDate() + i)
);
let month = new Date(d).toLocaleString("default", {
month: "long"
});
let dateOfMonth = new Date(d).getDate();
let dayOfWeek = new Date(d).toLocaleString("default", {
weekday: "short"
});
// #ts-ignore
appointmentDates[dayOfWeek + ". " + month + " " + dateOfMonth] = [];
}
};
sortAppointmentsByDate = () => {
const { apptList } = this.props;
let dates: string[] = [];
dates = Object.keys(appointmentDates);
apptList.map((appt: AppointmentQuery) => {
return dates.map(date => {
if (
new Date(appt.appointmentTime).getDate().toString() ===
// #ts-ignore
date.match(/\d+/)[0]
) {
// #ts-ignore
appointmentDates[date].push(appt);
}
return null;
});
});
};
render() {
let list: any = appointmentDates;
return (
<section id="appointmentContainer">
{Object.keys(appointmentDates).map(date => {
return (
<div className="appointmentDateColumn" key={date}>
<span className="appointmentDate">{date}</span>
{list[date].map(
(apptInfo: AppointmentQuery, i: number) => {
return (
<AppointmentCard
key={i}
apptInfo={apptInfo}
/>
);
}
)}
</div>
);
})}
</section>
);
}
}
appointmentDates should really be a local component state object, then when you update it in a lifecycle function react will correctly rerender and you won't need to force anything. OR since you aren't doing anything other than computing formatted data to render, Appointments should just call setAppointmentDates and sortAppointmentsByDate in the render function.
Good afternoon,
I am attempting to set and clear an interval. I assign the interval to my state because attempting to declare it anywhere else either isn't allowed (when declared outside of a function) or is limited by scope (when declared inside of a function) or is otherwise inaccessible (when declared outside of the class). My code is as follows (It's still very much in the testing stage so it's pretty rough. It is doing what I want it to though, short of clearing the interval):
import React, { Component, lazy, Suspense } from 'react';
const Passersby = lazy(() => import('../components/Passersby'));
class Public extends Component {
state = {
passersby: null,
intervalStorer: null
};
startJeff = () => {
this.setState({ passersby: null });
import('axios').then(axios => {
axios.get('http://localhost:8080/get_jeff')
});
setTimeout(this.stopIt, 10000);
//remember to call clearTimeout() if defeat conditions are satisfied
this.checkForJeff();
}
checkForJeff = () => {
if (this.state.passersby === null) {
this.setState({ passersby: [] });
}
this.queryForJeff();
}
queryForJeff = () => {
//setInterval() returns an numerical code, correct? Why isn't it being stored here?
const interval = setInterval(this.assignJeff, 1000);
this.setState({ intervalStorer: interval });
}
assignJeff = () => {
console.log('looked for jeff')
import('axios').then(axios => {
axios.get('http://localhost:8080/get_jeff/more_jeffs')
.then(response => {
const folks = response.data;
const updatePassersby = this.state.passersby;
updatePassersby.push.apply(updatePassersby, folks);
this.setState({ passersby: updatePassersby });
});
});
}
stopIt = () => {
//this logs in the console as "undefined"
console.log(this.intervalStorer);
clearInterval(this.intervalStorer);
import('axios').then(axios => {
axios.get('http://localhost:8080/get_jeff/stop_jeff')
});
}
render() {
let people = null;
if (this.state.passersby) {
people = (
<Passersby
name={this.state.passersby.name}
activity={this.state.passersby.activity}
key={this.state.passersby.id}
passersby={this.state.passersby}
/>
)
}
return <div>
<h1>Jeffs?</h1>
<button onClick={this.startJeff}>Start the Jeffing</button>
<button onClick={this.checkForJeff}>More Possible Jeffs?</button>
<button onClick={this.postInterval}>Interval Test</button>
<button onClick={this.stopIt}>NO MORE JEFFS</button>
<Suspense fallback={<div>Jeff Could Be Anywhere...</div>}>
{people}
</Suspense>
</div>
}
}
export default Public;
What do I need to do to get the setInterval() stored properly in my state?
Thanks.
You are accessing your state variable incorrectly,
access it as
this.state.intervalStorer
this.intervalStorer is considered as an uninitialized local variable, that's why it is returning you undefined.
I have function for set my state from another class, but i got this following error
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
And here's my code looks like
constructor(props) {
super(props)
this.state = { loading: true, showAction: false }
setTimeout(() => {
StatusBar.setBackgroundColor(primary)
}, 100)
}
async componentWillMount() {
await Font.loadAsync({
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
Ionicons: require("#expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/Ionicons.ttf"),
});
this.setState({ loading: false });
}
setShowAction = (isShowAction) => {
console.log(isShowAction)
this.setState({
showAction: isShowAction
})
}
...
<ChatListScreen onAction={(isShowAction) => this.setShowAction(isShowAction)}/>
...
const ChatListScreen = ({ onAction }) => {
return (
<ChatList onAction={(isShowAction) => onAction(isShowAction)}/>
)
}
...
const ChatList = ({ onAction }) => {
const [selectMode, setSelectMode] = useState(false)
const chatListDummy = []
const [selectedItem, setSelectedItem] = useState([])
{selectMode ? onAction(true) : onAction(false)}
return (
<FlatList
data= {chatListDummy}
keyExtractor= {chat => chat.id}
renderItem= {({item}) => {
}}/>
)
}
export default ChatList
Can anyone help?
see my solution
const ChatListScreen = ({ onAction }) => {
return (
<ChatList onAction={(isShowAction) => onAction(isShowAction)}/>
)
}
const ChatList = ({ onAction }) => {
const [selectMode, setSelectMode] = useState(false)
const [selectedItem, setSelectedItem] = useState([])
//i dont know where are you using this actally you most use this in a lifesycle or a function
// {selectMode ? onAction(true) : onAction(false)}
function onClick(){
selectMode ? onAction(true) : onAction(false)
}
//or a lifecycle
useEffect(()=>{
selectMode ? onAction(true) : onAction(false)
},[])
return (<div onClick ={onClick} >{"your content"}</div>)
Try to avoid passing anonymous functions as props to React components. This is because React will always re render your component as it will fail to compare its state to the previous one, which too is an anonymous function.
Having said that, there will be some cases in which passing anonymous functions would be unavoidable. In that case, never update your state inside the anonymous function. This is the main problem in your scenario, here is whats happening:
You pass anonymous function as a prop to your component.
When component receives this function, it is failed to compare it with the previous state and hence re renders your component.
Inside your anonymous function, you are updating your state. Updating your state would force React to re render component again.
this.setState({
showAction: isShowAction
}) //this portion is mainly responsible for the error
Hence this cycle continues up till a threshold till React throws an error Maximum update depth exceeded.
I am setting state inside a function which I call in componentDidMount(), but I am not accessing the value of state in the render.
How to access the state inside the render method on time?
state:
constructor() {
super();
this.state = {
check_for_amount: '',
};
}
componentdidmount() :
componentDidMount() {
this.check_amount_left();
}
function:
check_amount_left = () => {
const getSelected = this.props.navigation.state.params;
var ref = firebase.firestore().collection('discounts').where("rest_id", "==", getSelected.rest_id)
ref.onSnapshot((querySnapshot => {
var amount = querySnapshot.docs.map(doc => doc.data().amount);
this.setState({
check_for_amount: amount
});
}));
}
Render:
render() {
return(
<View/>
<Text>
{this.state.check_for_amount}
</Text>
</View>
)
}
You got wrong () at onSnapshot. Please check below to see it works for you. If not, try to log inside onSnapshot to see if it called properly.
check_amount_left = () => {
const getSelected = this.props.navigation.state.params;
var ref = firebase.firestore().collection('discounts').where("rest_id", "==", getSelected.rest_id)
ref.onSnapshot(querySnapshot => {
var amount = querySnapshot.docs.map(doc => doc.data().amount);
this.setState({
check_for_amount: amount
});
});
}
I am fetching data from an API. I am building an array of 5 objects using the API call. What I am trying to do is iterate over the array, use the data inside each array index to build a component and pass along the props to another component.
I've tried accessing the element the same way I normally would by doing:
img={pokemon.name} but it keeps returning undefined. When I type in
console.log(pokemon) I get the individual pokemon stored within the array of objects.
import React, { Component } from "react";
import Pokecard from "./Pokecard";
async function getPokemon() {
const randomID = Math.floor(Math.random() * 151) + 1;
const pokeRes = await fetch(`https://pokeapi.co/api/v2/pokemon/${randomID}/`);
const pokemonJSON = await pokeRes.json();
return pokemonJSON;
}
function buildPokemon() {
let pokemonArr = [];
let builtPokemon = {};
getPokemon()
.then(data => {
builtPokemon.name = data.forms[0].name;
builtPokemon.exp = data.base_experience;
builtPokemon.img = data.sprites.front_default;
builtPokemon.type = data.types[0].type.name;
pokemonArr.push(builtPokemon);
})
.catch(err => console.log(err));
return pokemonArr;
}
class Pokedex extends Component {
constructor(props) {
super(props);
this.state = { pokemonArr: [] };
}
componentDidMount() {
const pokemonArr = [];
for (let i = 0; i < 5; i++) {
pokemonArr.push(buildPokemon());
}
this.setState({ pokemonArr });
}
render() {
console.log(this.state.pokemonArr);
return (
<div className="Pokedex">
{this.state.pokemonArr.map(pokemon => console.log(pokemon))}
</div>
);
}
}
export default Pokedex;
What should happen is that when I map the pokemonArr I want to create 5 separate pokemon by doing
this.state.pokemonArr.map(pokemon => <Pokecard name={pokemon.name} but I keep getting undefined whenever I check this.props in the Pokecard component.
I think my buildPokemon() function is working because when I call it in the componentDidMount() and then I console.log this.state.pokemonArr in the render() function, I actually get an array returned with 5 different pokemon with the proper fields filled out.
And also when I map out this.state.pokemonArr.map(pokemon => clg(pokemon)), it actually displays each individual pokemon. When I pass the pokemon item into a component like this
<Pokecard name={pokemon}/>, I see all the pokemon data.
when I type <Pokecard name={pokemon.name} I get undefined
There are several problems with your approach but the main one is that getPokemon() is asynchronous.
Return the getPokemon() promise from buildPokemon() and return the object from it's then()
In your for() loop create an array of these promises and use Promise.all() to set state once they have all resolved
function buildPokemon() {
let builtPokemon = {};
// return the promise
return getPokemon()
.then(data => {
builtPokemon.name = data.forms[0].name;
builtPokemon.exp = data.base_experience;
builtPokemon.img = data.sprites.front_default;
builtPokemon.type = data.types[0].type.name;
// return the object
return builtPokemon
});
}
componentDidMount() {
const pokemonPromises = [];
for (let i = 0; i < 5; i++) {
pokemonPromises.push(buildPokemon());
}
Promise.all(pokemonPromises).then(pokemonArr => this.setState({ pokemonArr }));
}
componentDidMount executes after first render, initially your state is pokemonArr: [] (whch is empty) so you are getting an error. You need to conditionally render like,
{this.state.pokemonArr.length > 0 && this.state.pokemonArr.map(pokemon => console.log(pokemon))}
Side Note:
In buildPokemon function you are returning an array, and again in componentDidMount you are storing it in array which creates array of array's, you just need to return object from buildPokemon function.
The problem is mainly how the Promise should be resolved.
The data isn't available right away so the state (pokemonArr) should only be set once data is available.
Here's the refactored component:
class Pokedex extends Component {
constructor(props) {
super(props);
this.state = { pokemonArr: [] };
}
componentDidMount() {
for (let i = 0; i < 5; i++) {
this.getPokemon()
.then((pokemon) => this.buildPokemon(pokemon));
}
}
async getPokemon() {
const randomID = Math.floor(Math.random() * 151) + 1;
const pokeRes = await fetch(`https://pokeapi.co/api/v2/pokemon/${randomID}/`);
return pokeRes.json();
}
setPokemon(pokemon) {
this.setState({
pokemonArr: [
...this.state.pokemonArr, pokemon
],
});
}
buildPokemon(data) {
let builtPokemon = {};
builtPokemon.name = data.forms[0].name;
builtPokemon.exp = data.base_experience;
builtPokemon.img = data.sprites.front_default;
builtPokemon.type = data.types[0].type.name;
this.setPokemon(builtPokemon);
}
render() {
return (
<div className="Pokedex">
{this.state.pokemonArr.map(pokemon => console.log(pokemon))}
</div>
);
}
}