When this component is called I get the follow error.
setState(...): Cannot update during an existing state transition (such
as within render or another component's constructor). Render methods
should be a pure function of props and state; constructor side-effects
are an anti-pattern, but can be moved to componentWillMount.
It seems to be because { this.renderCurrentAthlete() } inside render. When I call renderCurrentAthlete I'm trying to let state know who the current Athlete is by running the this.setState({ currentAthlete: currentAthleteData.Athlete }) but it causes an error. Any advise on how to handle this properly? Also any other advise on the component would be awesome too! Learning so all info is a great help :)
class MiniGame extends Component {
constructor(props){
super(props);
this.state = {
score: 0,
currentAthlete: null
}
}
gameData = [
{Athlete: "Peyton Manning", Img: "someURL"},
{Athlete: "Tony Hawk", Img: "someURL"},
{Athlete: "Tomy Brady", Img: "someURL"},
{Athlete: "Usain Bolt", Img: "someURL"}
]
renderGameButtons() {
return(
<div>
{this.gameData.map((x) => {
return(
<div key={x.Athlete}>
<button className="btn btn-outline-primary" onClick={ () => this.answerHandler(x.Athlete)}> {x.Athlete} </button>
</div>
)
})}
</div>
)
}
renderCurrentAthlete() {
const currentAthleteData = this.gameData[Math.floor(Math.random() * 4)];
//console.log(currentAthleteData);
const imgUrl = currentAthleteData.Img;
const athleteName = currentAthleteData.Athlete;
console.log(imgUrl, athleteName);
//console.log(currentAthlete);
this.setState({ currentAthlete: currentAthleteData.Athlete });
return(
<img className="card-img-top imgCard" src={imgUrl} alt="..."></img>
)
}
answerHandler(answer){
// console.log(a)
// console.log(this.state.currentAthlete)
if(answer === this.state.currentAthlete) {
this.setState({score: this.state.score + 10})
console.log(this.state.score);
}
}
render(){
return(
<div className="miniGameContainer">
<div className="card card-outline-info mb-3">
{ this.renderCurrentAthlete() }
<div className="card-block">
<p className="card-text">Pick your Answer Below</p>
{ this.renderGameButtons() }
</div>
</div>
</div>
)
}
}
Add method componentWillMount put this code to it and remove from renderCurrentAthlete. method componentWillMount will invoke before render. See more react lifecycle
componentWillMount() {
const currentAthleteData = this.gameData[Math.floor(Math.random() * 4)];
//console.log(currentAthleteData);
const imgUrl = currentAthleteData.Img;
const athleteName = currentAthleteData.Athlete;
console.log(imgUrl, athleteName);
//console.log(currentAthlete);
this.setState({ currentAthlete: currentAthleteData.Athlete });
}
Related
I'm running into the issue where I have created a functional component to render a dropdown menu, however I cannot update the initial state in the main App.JS. I'm not really sure how to update the state unless it is in the same component.
Here is a snippet of my App.js where I initialize the items array and call the functional component.
const items = [
{
id: 1,
value:'item1'
},
{
id: 2,
value:'item2'
},
{
id: 3,
value:'item3'
}
]
class App extends Component{
state = {
item: ''
}
...
render(){
return{
<ItemList title = "Select Item items= {items} />
And here is my functional componenet. Essentially a dropdown menu from a YouTube tutorial I watched (https://www.youtube.com/watch?v=t8JK5bVoVBw).
function ItemList ({title, items, multiSelect}) {
const [open, setOpen] = useState (false);
const [selection, setSelection] = useState([]);
const toggle =() =>setOpen(!open);
ItemList.handleClickOutside = ()=> setOpen(false);
function handleOnClick(item) {
if (!selection.some(current => current.id == item.id)){
if (!multiSelect){
setSelection([item])
}
else if (multiSelect) {
setSelection([...selection, item])
}
}
else{
let selectionAfterRemoval = selection;
selectionAfterRemoval = selectionAfterRemoval.filter(
current =>current.id == item.id
)
setSelection([...selectionAfterRemoval])
}
}
function itemSelected(item){
if (selection.find(current =>current.id == item.id)){
return true;
}
return false;
}
return (
<div className="dd-wraper">
<div tabIndex={0}
className="dd-header"
role="button"
onKeyPress={() => toggle(!open)}
onClick={() =>toggle(!open)}
onChange={(e) => this.setState({robot: e.target.value})}
>
<div className="dd-header_title">
<p className = "dd-header_title--bold">{title}</p>
</div>
<div className="dd-header_action">
<p>{open ? 'Close' : 'Open'}</p>
</div>
</div>
{open && (
<ul className ="dd-list">
{item.map(item =>(
<li className="dd-list-item" key={item.id}>
<button type ="button"
onClick={() => handleOnClick(item)}>
<span>{item.value}</span>
<span>{itemSelected(item) && 'Selected'}</span>
</button>
</li>
))}
</ul>
)}
</div>
)
}
const clickOutsideConfig ={
handleClickOutside: () => RobotList.handleClickOutside
}
I tried passing props and mutating the state in the functional component, but nothing gets changed. I suspect that it needs to be changed in the itemSelected function, but I'm not sure how. Any help would be greatly appreciated!
In a function component, you have the setters of the state variables. In your example, you can directly use setOpen(...) or setSelection(...). In case of a boolean state variable, you could just toggle by using setOpen(!open). See https://reactjs.org/docs/hooks-state.html (Chapter "Updating State") for further details.
So you need to do something like below . Here we are passing handleChange in parent Component as props to the child component and in Child Component we are calling the method as props.onChange
Parent Component:
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
value :''
}
}
handleChange = (newValue) => {
this.setState({ value: newValue });
}
render() {
return <Child value={this.state.value} onChange = {this.handleChange} />
}
}
Child Component:
function Child(props) {
function handleChange(event) {
// Here, we invoke the callback with the new value
props.onChange(event.target.value);
}
return <input value={props.value} onChange={handleChange} />
}
Im building a simple spotify app using react for the first time. Currenty I am able to render the current track being played by a user with it automatically appearing on the page. If I change tracks quickly(within a few seconds) it renders the new track details on to the page. However if I wait a couple of seconds, it stops rendering. Any reason why?
below is an example of my code
return (
<div className="App">
<a href='http://localhost:8888'>
<button>Login But With Spotify</button>
</a>
{this.getNowPlaying()}
<div> Now Playing: { this.state.nowPlaying.name} </div>
<div> By: { this.state.nowPlaying.artist} </div>
<div> Id: { this.state.nowPlaying.id} </div>
<div>
<img src={ this.state.nowPlaying.image} style={{ width: 100}}/>
</div>
</div>
)
}
Any help would be great :)
It is because you invoked the API call method "getNowPlaying" inside render method.
Each render cycle of react will call the render method, so it may be called many times.
Remove the {this.getNowPlaying()} from render and create a method "componentDidMount" and place it there. (see the code below)
The "componentDidMount" method is a react's component lifecycle method called after the component successfully mounted (initialized).
Read more in react's class component lifecycle methods docs
import React, { Component } from 'react';
import './App.css';
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)
}
}
componentDidMount() {
this.getNowPlaying()
}
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[1].url,
artist: response.item.artists[0].name,
id: response.item.id
}
})
}
)
}
render() {
return (
<div className="App">
<a href='http://localhost:8888'>
<button>Login But With Spotify</button>
</a>
<div> Now Playing: { this.state.nowPlaying.name} </div>
<div> By: { this.state.nowPlaying.artist} </div>
<div> Id: { this.state.nowPlaying.id} </div>
<div>
<img src={ this.state.nowPlaying.image} style={{ width: 100}}/>
</div>
</div>
)
}
}
Ok, this is some basic stuff.
Basically in your code, you get the new stuff on every rerender. Here there is the problem, the rerender happens only when a state, the parent or (not always) a prop changes. This can lead to some issues.
You see it working, because you change song before the This.setState is fired, so when setting the state, it triggers the component to rerender, which calls the function again. At this point, if the response has changed (basicly if you change the song), the state gets updated and this step is repeated, else, if the response is the same (didn't change the song in the meantime), the state doesn't change (leading the component not to rerender --> not refetching the data);
Here you can find the solution(s). One is class component, one is hooks (i've tested only the hooks' one). I personally would recommend the second one, because it's less code, more flexible and easier to understand!
I hope i could help you!
Class Component
import React, { Component } from 'react';
import './App.css';
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;
}
componentDidMount(){
this.getNowPlaying();
}
getNowPlaying(){
spotifyWebApi.getMyCurrentPlaybackState()
.then((response) => {
this.setState({
nowPlaying: {
name: response.item.name,
image: response.item.album.images[1].url,
artist: response.item.artists[0].name,
id: response.item.id
}
})
this.getNowPlaying();
}
)
}
render() {
return (
<div className="App">
<a href='http://localhost:8888'>
<button>Login But With Spotify</button>
</a>
<div> Now Playing: { this.state.nowPlaying.name} </div>
<div> By: { this.state.nowPlaying.artist} </div>
<div> Id: { this.state.nowPlaying.id} </div>
<div>
<img src={ this.state.nowPlaying.image} style={{ width: 100}}/>
</div>
</div>
)
}
}
Hooks
import React, { useState, useEffect, useCallback } from "react";
import "./App.css";
import Spotify from "spotify-web-api-js";
const spotifyWebApi = new Spotify();
function App() {
//not used?
const [loggedIn, setLoggedIn] = useState();
//telling whether the component is mount or not
const [isComponentMount,setIsComponentMount]=useState(true);
//response container
const [nowPlaying, setNowPlaying] = useState({
name: "Not Checked",
image: "",
artist: "",
id: ""
});
//Fetches the newest data
const getNowPlaying = useCallback(() => {
//Needed to stop the infinite loop after the component gets closed
if(!isComponentMount)return;
spotifyWebApi.getMyCurrentPlaybackState().then(response => {
setNowPlaying({
name: response.item.name,
image: response.item.album.images[1].url,
artist: response.item.artists[0].name,
id: response.item.id
});
//Change this one as you like (perhaps a timeout?)
getNowPlaying();
});
}, []);
useEffect(() => {
//Get hash params
const params = {};
var e,
r = /([^&;=]+)=?([^&;]*)/g,
q = window.location.hash.substring(1);
while ((e = r.exec(q))) {
params[e[1]] = decodeURIComponent(e[2]);
}
if (params.access_token) {
spotifyWebApi.setAccessToken(params.access_token);
}
getNowPlaying();
return ()=>{
setIsComponentMount(false);
}
}, [getNowPlaying]);
return (
<div className="App">
<a href="http://localhost:8888">
<button>Login But With Spotify</button>
</a>
<div> Now Playing: {nowPlaying.name} </div>
<div> By: {nowPlaying.artist} </div>
<div> Id: {nowPlaying.id} </div>
<div>
<img src={nowPlaying.image} style={{ width: 100 }} alt="" />
</div>
</div>
);
}
export default App
I'm trying to do unit testing to a component using enzyme shallow rendering. Trying to test state activeTab of the component and it throws TypeError: Cannot read property state. my component Accordion. Accordion component jsx code
class Accordion extends Component {
constructor(props) {
super(props)
this.state = {
activeTab: 0
}
}
static defaultProps = {
tabs: [{title: 'Status'}, {title: 'Movement'}]
}
render() {
const { tabs } = this.props
, { activeTab } = this.state
return (
<div className={`accordion`}>
{tabs.map((t, i) => {
const activeClass = activeTab === i ? `accordion--tab__active` : ''
return(
<section key={i} className={`accordion--tab ${activeClass}`}>
<header className={`accordion--header`}>
<h4 className={`accordion--title`}>
<button onClick={() => {this._selectAccordion(i)}}>{t.title}</button>
</h4>
</header>
<div className="accordion--content">
{t.title}
Content
</div>
</section>
)
})}
</div>
)
}
_selectAccordion = activeTab => {this.setState({activeTab})}
}
export default Accordion
and Accordion.react.test.js
import { shallow } from 'enzyme'
import Accordion from './components/Accordion'
test('Accordion component', () => {
const component = shallow(<Accordion name={`Main`}/>)
expect(component.state('activeTab')).equals(0)
})
This could be a this scoping issue. With event handlers in React, you have to bind the event handler in the constructor to "this". Here is some info from React's docs about it:
You have to be careful about the meaning of this in JSX callbacks. In
JavaScript, class methods are not bound by default. If you forget to
bind this.handleClick and pass it to onClick, this will be undefined
when the function is actually called.
This is not React-specific behavior; it is a part of how functions
work in JavaScript. Generally, if you refer to a method without ()
after it, such as onClick={this.handleClick}, you should bind that
method.
class Accordion extends Component {
constructor(props) {
super(props)
this.state = {
activeTab: 0
}
// This binding is necessary to make `this` work in the callback
this._selectAccordion = this._selectAccordion.bind(this);
}
static defaultProps = {
tabs: [{title: 'Status'}, {title: 'Movement'}]
}
_selectAccordion(activeTab){
this.setState({activeTab : activeTab})
}
render() {
const { tabs } = this.props,
{ activeTab } = this.state
return (
<div className={`accordion`}>
{tabs.map((t, i) => {
const activeClass = activeTab === i ? `accordion--tab__active` : ''
return(
<section key={i} className={`accordion--tab ${activeClass}`}>
<header className={`accordion--header`}>
<h4 className={`accordion--title`}>
<button onClick={() => {this._selectAccordion(i)}}>{t.title}</button>
</h4>
</header>
<div className="accordion--content">
{t.title}
Content
</div>
</section>
)
})}
</div>
)
}
}
Your tests should verify how the component works but not "how to change a state". You need to throw new props into your component and get a result, and the result is expected.
I've tested my components with snapshots
This is an example of my current project
describe('<Component />', () => {
it('Page rendered', () => {
const rendered = renderComponent({
...testProps,
loadDataList,
loading: true,
});
expect(rendered).toMatchSnapshot();
});
});
I'm having problems trying to render two react elements inside a react component after a onClick event. Wondering if that's even possible? I'm sure I'm messing up the ternary operator, but I cannot think on another way to do what I'm trying to do ?
TL;DR: "When I click a button I see elementA and elementB"
Here is a snippet of the code:
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = { showElement: true };
this.onHandleClick = this.onHandleClick.bind(this);
}
onHandleClick() {
console.log(`current state: ${this.state.showElement} and prevState: ${this.prevState}`);
this.setState(prevState => ({ showElement: !this.state.showElement }) );
};
elementA() {
<div>
<h1>
some data
</h1>
</div>
}
elementB() {
<div>
<h1>
some data
</h1>
</div>
}
render() {
return (
<section>
<button onClick={ this.onHandleClick } showElement={this.state.showElement === true}>
</button>
{ this.state.showElement
?
null
:
this.elementA() && this.elementB()
}
</section>
)
}
}
export default MyComponent;
You just inattentive.
elementA() {
return ( // You forget
<div>
<h1>
some data
</h1>
</div>
)
}
And the same in element B.
And if You want to see both components you should change Your ternary to
{ this.state.showElement
?
<div> {this.elementA()} {this.elementB()}</div>
:
null
}
Another "and", for toggling showElement in state just enough
this.setState({showElement: !this.state.showElement });
Try this instead, (I will add comments into the code trying to explain what's going on):
function SomeComponentName() { // use props if you want to pass some data to this component. Meaning that if you can keep it stateless do so.
return (
<div>
<h1>
some data
</h1>
</div>
);
}
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = { showElement: false }; // you say that initially you don't want to show it, right? So let's set it to false :)
this.onHandleClick = this.onHandleClick.bind(this);
}
onHandleClick() {
this.setState(prevState => ({ showElement: !prevState.showElement }) );
// As I pointed out in the comment: when using the "reducer" version of `setState` you should use the parameter that's provided to you with the previous state, try never using the word `this` inside a "reducer" `setState` function
};
render() {
return (
<section>
<button onClick={ this.onHandleClick } showElement={this.state.showElement === false}>
</button>
{ this.state.showElement
? [<SomeComponentName key="firstOne" />, <SomeComponentName key="secondOne" />]
: null
}
</section>
)
}
}
export default MyComponent;
First watch this, so you can see the behavior going on.
Timing Issue (JS in one component relies on another component to exist first)
I need to be able to somehow check that another component exists before I apply this JS in this component's ComponentDidMount
const TableOfContents = Component({
store: Store('/companies'),
componentDidMount() {
const el = ReactDOM.findDOMNode(this);
console.log("table of contents mounted");
if(document.getElementById('interview-heading') && el) {
new Ink.UI.Sticky(el, {topElement: "#interview-heading", bottomElement: "#footer"});
}
},
it does hit my if statement and does hit the Sticky() function but I still think I have problems when I refresh the page whereas this JS isn't working on the interview-heading component for some reason.
Note the id="interview-heading" below.
const InterviewContent = Component({
componentDidMount() {
console.log("InterviewContent mounted");
},
render(){
var company = this.props.company;
return (
<div id="ft-interview-content">
<p className="section-heading bold font-22" id="interview-heading">Interview</p>
<InterviewContentMain company={company}/>
</div>
)
}
})
const InterviewContentMain = Component({
componentDidMount() {
console.log("InterviewContentMain mounted");
},
render(){
var company = this.props.company;
return (
<div id="interview-content" className="clear-both">
<div className="column-group">
<div className="all-20">
<TableOfContents company={company}/>
</div>
<div className="all-80">
<InterviewContainer company={company}/>
</div>
</div>
</div>
)
}
})
export default InterviewContent;
I realize TableOfContents is being rendered before InterviewContent because it's a child of TableOfContents and I believe in React children are rendered before their parents (inside-out)?
I think you need to rethink your component structure. I don't know your entire setup, but it looks like you should probably have a shared parent component pass the message from TableOfContents to InterviewContent:
const InterviewContentMain = Component({
getInitialState() {
return {
inkEnabled: false
}
},
componentDidMount() {
console.log("InterviewContentMain mounted");
},
enableInk() {
this.setState({ inkEnabled: true });
}
render(){
var company = this.props.company;
return (
<div id="interview-content" className="clear-both">
<div className="column-group">
<div className="all-20">
<TableOfContents inkEnabled={this.state.inkEnabled} company={company}/>
</div>
<div className="all-80">
<InterviewContainer enableInk={this.enableInk} company={company}/>
</div>
</div>
</div>
)
}
})
const TableOfContents = Component({
store: Store('/companies'),
componentDidMount() {
console.log("table of contents mounted");
this.props.enableInk();
},
...
const InterviewContent = Component({
enableInk() {
new Ink.UI.Sticky(el, {topElement: "#interview-heading", bottomElement: "#footer"});
},
// willReceiveProps isn't called on first mount, inkEnabled could be true so
componentDidMount() {
if (this.props.inkEnabled) {
this.enableInk();
}
},
componentWillReceiveProps(nextProps) {
if (this.props.inkEnabled === false && nextProps.inkEnabled === true) {
this.enableInk();
}
}
render(){
var company = this.props.company;
return (
<div id="ft-interview-content">
<p className="section-heading bold font-22" id="interview-heading">Interview</p>
<InterviewContentMain company={company}/>
</div>
)
}
})
Then have componentDidMount trigger this.props.enableInk().
Or better yet, why not just put the Ink.UI.Sticky call in componentDidMount of InterviewContent?