componentWillReceiveProps this.props and nextProps always the same - javascript

I have a parent component ProductTest that holds state as the source of truth. The state is an array of variant items. Each item is simplified for this example and has a title.
When a Variant's title is updated, the child will call it's handler callback via the prop passed by the parent. The parent then updates state, and the child will then have a new title property.
What I am seeing is that the child's componentWillReceiveProps function will display the same value for this.props and nextProps. I would think that since the value is supplied by the parent, the two would be different.
I'm not sure what I'm doing incorrectly.
Here is the parent ProductTest component:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import axios from 'axios'
import Variant from './variants/Variant'
import { REACT_APP_API_URL, REACT_APP_SITE_KEY } from '../../../shared/vars'
import '../../../css/variants.css'
class ProductTest extends Component {
constructor(props) {
super(props)
this.state = {
variants: []
}
this.handleVariantTitleChange = this.handleVariantTitleChange.bind(this)
this.handleVariantValueChange = this.handleVariantValueChange.bind(this)
}
componentDidMount() {
this.loadData()
}
loadData() {
const apiEndpoint = 'products/some-product'
const AUTH_HEADER = { Authorization: REACT_APP_SITE_KEY }
return axios.get(REACT_APP_API_URL + apiEndpoint, { headers: AUTH_HEADER })
.then((response) => {
this.setState({ variants: response.data.product.variants })
})
.catch((err) => {
console.log("YA GOOFED BUD!", err)
})
}
handleVariantTitleChange(e, i) {
let { variants } = this.state
const { value } = e.target
variants = variants.map((item, index) => {
item.title = i === index ? value : item.title
return item
})
this.setState({ variants })
}
handleVariantValueChange(e, id) {
let { variants } = this.state
const { value } = e.target
variants = variants.map(variant => {
variant.items = variant.items.map(item => {
item.title = id === item.id ? value : item.title
return item
})
return variant
})
this.setState({ variants })
}
render() {
return (
<div>
{this.state.variants.map((variant, i) => {
return <Variant key={i}
variant={variant}
index={i}
changeVariantTitle={this.handleVariantTitleChange}
changeVariantValue={this.handleVariantValueChange}
/>
})}
</div>
)
}
}
export default ProductTest
Here is the child Variant component:
import React, { Component } from 'react'
class Variant extends Component {
componentWillReceiveProps(nextProps){
console.log(this.props, nextProps)
}
render() {
const { variant, index } = this.props
return (
<div className="variant-wrapper" data-new="new_value">
<div className="ajax-error" data-hbs-id="{{id}}"></div>
<div className="varient-item-titles">
<div className="variant-item-title">
Title
</div>
<div className="varient-attribute-titles">
<div className="variant-attribute">Value</div>
</div>
</div>
<div className="variant-item-content">
<div className="variant-label">
<input type="text" name="variant_label" value={variant.title} placeholder="Size, colour, etc."
onChange={e => this.props.changeVariantTitle(e, index)}
/>
</div>
</div>
</div>
)
}
}
export default Variant
Before
After
Console.log()
These two objects are this.props and nextProps. Notice the title property is not different, as I'd expect them to be.
SOLUTION!
The reason for all of those is that I was not correctly altering the parent's state immutably. I think I was just changing the value at the same memory address, and hence by the time it got to the componentWillReceiveProps it was already the new value. I think...
I found that the following will work:
handleVariantTitleChange(e, i){
const { value } = e.target
// Immutably clone specific variant item
let variant = Object.assign({}, this.state.data.variants[i])
// Set new title to item
variant.title = value
// Set the variant to the cloned item
let variants = this.state.data.variants
variants[i] = variant
this.setState({
data: {
...this.state.data,
variants
}
})
}

Related

In React Context, how can I use state variables in state functions?

I have a React Context which looks like this:
import React, { Component } from 'react'
const AlertsContext = React.createContext({
categoryList: [],
setCategoryList: () => {}
})
export class AlertsProvider extends Component {
state = {
categoryList: [],
setCategoryList: categoryString => (
this.categoryList.includes(categoryString)
? this.setState({ categoryList: this.categoryList.filter(value => value !== categoryString) })
: this.setState({ categoryList: this.categoryList.concat([categoryString]) })
)
}
render() {
const { children } = this.props
const {categoryList, setCategoryList } = this.state
return (
<AlertsContext.Provider value={{categoryList, setCategoryList}}>
{children}
</AlertsContext.Provider>
)
}
}
export const AlertsConsumer = AlertsContext.Consumer
So, categoryList is an array of strings, each representing a category. setCategoryList should take a string; if that string is already in the array, it removes it, and if it's not in the array it adds it.
In one of my components the user can select categories from a list of checkboxes. When a checkbox is clicked, the AlertsContext setCategoryList should be called with the value of the clicked box:
import React, { Component } from 'react'
import { AlertsConsumer } from '../../../context/alerts-context'
class AlertFilters extends Component {
constructor(props) {
super(props)
this.state = {
categories: props.categories
}
}
render() {
const { categories } = this.state
return (
<AlertsConsumer>
{({ categoryList, setCategoryList }) => (
<>
{
categories.map(category => (
return (
<div key={category.id}>
<Checkbox id={category.id} value={category.value} onChange={e => setCategoryList(e.target.value)} checked={categoryList.includes(category.value)} />
<label htmlFor={category.id}>{category.value}</label>
</div>
)
))
}
</>
)}
</AlertsConsumer>
)
}
}
export default AlertFilters
This compiles ok, but when I run it and click a checkbox I get the following error:
alerts-context.jsx:77 Uncaught TypeError: Cannot read property 'includes' of undefined
This is in the line:
this.categoryList.includes(categoryString)
in the Context Provider, suggesting that "this.categoryList" is undefined at this point.
I tried changing it to
this.state.categoryList.includes(categoryString)
but it said I had to use state destructuring, so I changed to:
setCategoryList: (categoryString) => {
const { categoryList } = this.state
categoryList.includes(categoryString)
? this.setState({ categoryList: categoryList.filter(value => value !== categoryString) })
: this.setState({ categoryList: categoryList.concat([categoryString]) })
}
which highlighted the ternary operator and gave the following lint error:
Expected an assignment or function call and instead saw an expression.
What am I doing wrong?
Use if/else syntax to update the state.
setCategoryList: categoryString => {
const { categoryList } = this.state;
if (categoryList.includes(categoryString)) {
this.setState({
categoryList: categoryList.filter(value => value !== categoryString)
});
} else {
this.setState({ categoryList: categoryList.concat([categoryString]) });
}
};

React state one step behind (not duplicate!)

I know this may seem like a repeat and I have read the similar questions and answers. However I am still having an issue getting my parent component and its state to sync up with its child component. It is just one step behind, even in the console.
Parent Component App.js
changeItemQuantity = (id, newQuantity) => {
this.setState(prevState => ({
cartData: {
...prevState.cartData,
items: this.state.cartData.items.map(item => {
if (String(item.productData.productId) === String(id)) {
item.productQuantity = newQuantity
}
return item
})
}
}))
// console.log(id, newQuantity);
// console.log(this.state.cartData)
}
Child Component Cart.js
import React, { Component } from 'react';
class Cart extends Component {
constructor(props) {
super(props);
this.state = {
newQuantity: 1
}
}
handleQuantityChange = (e) => {
this.setState({
newQuantity: e.target.value
})
this.props.changeItemQuantity(e.target.id, this.state.newQuantity);
}
render() {
return (
<div className="cart-list">
{this.props.cartData.items.map(item => {
return (
<div className="cart-item" key={item.productData.productId}>
<div className={`cart-item-image ${item.productData.productImage}`}></div>
<div className="cart-item-data">
<div className="cart-item-name">{item.productData.productName}</div>
<div className="cart-item-s-q">( {item.productSize} ) x <input type="text" id={item.productData.productId} onChange={this.handleQuantityChange} className="cart-field change-q" placeholder={item.productQuantity}/></div>
<div className="cart-item-total">Total : ${(parseInt(item.productData.productPrice) * parseInt(item.productQuantity)).toFixed(2)}</div>
</div>
</div>
)
})}
</div>
)
}
}
export default Cart;
Basically what I am trying to accomplish is being able to be inside of the shopping cart page of my ecom site and adjust the quantity of each item (which is held inside of the parents state). I have that figured out, but when I adjust, the state inside the console and on the screen is not up to date. I have tried using a callback function like so
handleQuantityChange = (e) => {
this.setState({
newQuantity: e.target.value
}, this.props.changeItemQuantity(e.target.id, this.state.newQuantity);)
}
But that did nothing for me. I also tried using a callback inside of the Parent component like so...
changeItemQuantity = (id, newQuantity) => {
this.setState(prevState => ({
cartData: {
...prevState.cartData,
items: this.state.cartData.items.map(item => {
if (String(item.productData.productId) === String(id)) {
item.productQuantity = newQuantity
}
return item
})
}
}), console.log(this.state.cartData))
}
But again, nothing. What do you guys suppose I could do? Thanks in advance!

Filtering an Array within an Array in React

import React, { Component } from "react"
import {
StaticQuery,
grahpql,
Link
} from "gatsby"
import {
StyledFilter,
StyledLine
} from "./styled"
class Filter extends Component {
render() {
const { data } = this.props
const categories = data.allPrismicProjectCategory.edges.map((cat, index) => {
return (
<a
key={index}
onClick={() => this.props.setFilterValue(cat.node.uid)}
>
{cat.node.data.category.text}
</a>
)
})
return (
<StyledFilter>
<div>
Filter by<StyledLine />
<a
// onClick={() => {this.props.filterProjects("all")}}
>
All
</a>
{categories}
</div>
<a onClick={this.props.changeGridStyle}>{this.props.gridStyleText}</a>
</StyledFilter>
)
}
}
export default props => (
<StaticQuery
query={graphql`
query {
allPrismicProjectCategory {
edges {
node {
uid
data {
category {
text
}
}
}
}
}
}
`}
render={data => <Filter data={data} {...props} />}
/>
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I am working on a React App with Gatsby and Prismic that has a project page. By default it lists all projects but at the page's top appears a filter to select by category (just a bunch of <a> tags).
My Page consists of a <Filter /> component as well as several <GridItem /> components I am mapping over and load some props from the CMS.
The part I am struggling with is the filtering by category.
When my page component mounts it adds all projects into my filteredItems state.
When a user is clicking on a filter at the top it set's my default filterValue state from "all" to the according value.
After that I'll first need to map over the array of projects and within that array I'll need to map over the categories (each project can belong to multiple categories).
My idea is basically if a value (the uid) matches my new this.state.filterValue it returns the object and add's it to my filteredItems state (and of course delete the one's not matching this criteria).
This is what my page component looks like (cleaned up for better readability, full code in the snippet at the bottom):
class WorkPage extends Component {
constructor(props) {
super(props)
this.state = {
filterValue: "all",
filteredItems: []
}
this.filterProjects = this.filterProjects.bind(this)
}
filterProjects = (filterValue) => {
this.setState({ filterValue: filterValue }, () =>
console.log(this.state.filterValue)
)
// see a few of my approaches below
}
componentDidMount() {
this.setState({
filteredItems: this.props.data.prismicWork.data.projects
})
}
render() {
const projectItems = this.props.data.prismicWork.data.projects && this.props.data.prismicWork.data.projects.map((node, index) => {
const item = node.project_item.document["0"].data
const categories = node.project_item.document["0"].data.categories.map(cat => {
return cat.category_tag.document["0"].uid
})
return (
<GridItem
key={index}
categories={categories}
moreContentProps={moreContentProps}
/>
)
})
return (
<LayoutDefault>
<Filter
filterProjects={this.filterProjects}
/>
{projectItems}
</LayoutDefault>
)
}
}
I tried so many things, I can't list all of them, but here are some examples:
This approach always returns an array of 10 objects (I have 10 projects), sometimes the one's that don't match the this.state.filterValue are empty objects, sometimes they still return their whole data.
let result = this.state.filteredItems.map(item => {
return item.project_item.document["0"].data.categories.filter(cat => cat.category_tag.document["0"].uid === this.state.filterValue)
})
console.log(result)
After that I tried to filter directly on the parent item (if that makes sense) and make use of indexOf, but this always console logged an empty array...
let result = this.state.filteredItems.filter(item => {
return (item.project_item.document["0"].data.categories.indexOf(this.state.filterValue) >= 0)
})
console.log(result)
Another approach was this (naive) way to map over first the projects and then the categories to find a matching value. This returns an array of undefined objects.
let result = this.state.filteredItems.map(item => {
item = item.project_item.document["0"].data.categories.map(attachedCat => {
if (attachedCat.category_tag.document["0"].uid === this.state.filterValue) {
console.log(item)
}
})
})
console.log(result)
Other than that I am not even sure if my approach (having a filteredItems state that updates based on if a filter matches the according category) is a good or "right" React way.
Pretty stuck to be honest, any hints or help really appreciated.
import React, { Component } from "react"
import { graphql } from "gatsby"
import LayoutDefault from "../layouts/default"
import { ThemeProvider } from "styled-components"
import Hero from "../components/hero/index"
import GridWork from "../components/grid-work/index"
import GridItem from "../components/grid-item/index"
import Filter from "../components/filter/index"
class WorkPage extends Component {
constructor(props) {
super(props)
this.state = {
filterValue: "all",
filteredItems: [],
isOnWorkPage: true,
showAsEqualGrid: false
}
this.filterProjects = this.filterProjects.bind(this)
this.changeGridStyle = this.changeGridStyle.bind(this)
}
changeGridStyle = (showAsEqualGrid) => {
this.setState(prevState => ({
showAsEqualGrid: !prevState.showAsEqualGrid,
isOnWorkPage: !prevState.isOnWorkPage
}))
}
filterProjects = (filterValue) => {
this.setState({ filterValue: filterValue }, () =>
console.log(this.state.filterValue)
)
let result = this.state.filteredItems.filter(item => {
return (item.project_item.document["0"].data.categories.toString().indexOf(this.state.filterValue) >= 0)
})
console.log(result)
}
componentDidMount() {
this.setState({
filteredItems: this.props.data.prismicWork.data.projects
})
}
render() {
const projectItems = this.props.data.prismicWork.data.projects && this.props.data.prismicWork.data.projects.map((node, index) => {
const item = node.project_item.document["0"].data
const categories = node.project_item.document["0"].data.categories.map(cat => {
return cat.category_tag.document["0"].uid
})
return (
<GridItem
key={index}
isSelected="false"
isOnWorkPage={this.state.isOnWorkPage}
isEqualGrid={this.state.showAsEqualGrid}
projectURL={`/work/${node.project_item.uid}`}
client={item.client.text}
tagline={item.teaser_tagline.text}
categories={categories}
imageURL={item.teaser_image.squarelarge.url}
imageAlt={item.teaser_image.alt}
/>
)
})
return (
<ThemeProvider theme={{ mode: "light" }}>
<LayoutDefault>
<Hero
introline="Projects"
headline="Art direction results in strong brand narratives and compelling content."
/>
{/* {filteredResult} */}
<Filter
filterProjects={this.filterProjects}
changeGridStyle={this.changeGridStyle}
gridStyleText={this.state.showAsEqualGrid ? "Show Flow" : "Show Grid"}
/>
<GridWork>
{projectItems}
</GridWork>
</LayoutDefault>
</ThemeProvider>
)
}
}
export default WorkPage
export const workQuery = graphql`
query Work {
prismicWork {
data {
page_title {
text
}
# All linked projects
projects {
project_item {
uid
# Linked Content
document {
type
data {
client {
text
}
teaser_tagline {
text
}
teaser_image {
url
alt
xlarge {
url
}
large {
url
}
medium {
url
}
squarelarge {
url
}
squaremedium {
url
}
squaresmall {
url
}
}
categories {
category_tag {
document {
uid
data {
category {
text
}
}
}
}
}
}
}
}
}
}
}
}
`
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
So there are at least two things.
In your filterProjects() you're first setting state.filterValue and then you use it in filteredItems.filter(). That might not work, because React does not execute setState() immediately always, to optimize performance. So you're probably filtering against the previous value of state.filterValue. Instead just use filterValue, which you pass into filterProjects().
setFilterValue = (filterValue) => {
this.setState({filterValue}) // if key and variable are named identically, you can just pass it into setState like that
}
// arrow function without curly braces returns without return statement
filterProjects = (projects, filterValue) =>
projects.filter(item => item.project_item.document[0].data.categories.toString().includes(filterValue))
You should return the result from filterProjects(), because you need to render based on the filteredItems then, of course. But actually it's not necessary to put the filter result into state. You can apply the filterProjects() on the props directly, right within the render(). That's why you should return them. Also separate setState into another function which you can pass into your <Filter/> component.
And a recommendation: Use destructuring to make your code more readable. For you and anyone else working with it.
render() {
const { projects } = this.props.data.prismicWork.data // this is
const { filterValue } = this.state // destructuring
if (projects != undefined) {
this.filterProjects(projects, filterValue).map((node, index) => {
// ...
// Filter component
<Filter filterProjects={this.setFilterValue} />
That way you trigger a rerender by setting the filterValue, because it
resides in this.state, and the render function depends on
this.state.filterValue.
Please try that out and tell me if there is another problem.

Get consolidated data from all the child components in the form of an object inside a parent component : React JS

I am implementing a setting page for an application. For each setting I have implemented a slider that has enabled(green) or disabled(red) state. But parent's settings is read only and is calculated based on the values of its children.
Parent's setting is derived as follows: If all children are red, parent stays red ; If all are green parent stays green; If at-least one of child is green then parent stays grey(Pending).
These settings are grouped something like this:
Parent Feature 1 : (read-only-toggle)
Setting 1 (Toggle)
Setting 2 (Toggle)
Parent Feature 2: (read-only-toggle)
Setting 1 (Toggle)
Setting 2 (Toggle)
And in the end there is also a button, that gives me a consolidated values of all parent and children. But so far I was able to do only with one parent and 2 children.
Can someone help with an approach of getting consolidated values of all the settings in one place(Like a super parent component where all these settings are configured).
For this , I am using react-multi-toggle for this toggle switch.
Help would be really appreciated.
Code Sandbox: https://codesandbox.io/s/react-multi-toggle-solution-perfect-v9bi5
App
import React from "react";
import ChildSwitch from "./ChildSwitch";
import ParentSwitch from "./ParentSwitch";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
parentVal: "disabled",
switch1Val: "enabled",
switch2Val: "disabled"
};
}
componentDidMount() {
this.setParentSwitchValue();
}
onGetChildSwitchValues = () => {
console.log(this.state);
};
setChildSwitchValue = (whichSwitch, selected) => {
this.setState(
prevState => ({ ...prevState, [whichSwitch]: selected }),
this.setParentSwitchValue
);
};
setParentSwitchValue = () => {
const { switch1Val, switch2Val } = this.state;
const switchStates = [switch1Val, switch2Val];
let parent = "pending";
if (switchStates.every(val => val === "enabled")) {
parent = "enabled";
}
if (switchStates.every(val => val === "disabled")) {
parent = "disabled";
}
this.setState(prevState => ({ ...prevState, parentVal: parent }));
};
render() {
const { parentVal, switch1Val, switch2Val } = this.state;
return (
<>
<div className="boxed">
Parent Setting 1 :{" "}
<ParentSwitch
parentSwitch={parentVal}
onSelect={this.setParentSwitchValue}
/>
Setting 1:
<ChildSwitch
switchName={"switch1Val"}
selected={switch1Val}
onSelect={this.setChildSwitchValue}
/>
Setting 2:
<ChildSwitch
switchName={"switch2Val"}
selected={switch2Val}
onSelect={this.setChildSwitchValue}
/>
</div>
<button onClick={this.onGetChildSwitchValues}>Get All Values</button>
</>
);
}
}
ChildSetting
import MultiToggle from "react-multi-toggle";
import React from "react";
export default class ChildSwitch extends React.Component {
constructor(props) {
super(props);
this.state = {
options: [
{
displayName: "Disabled",
value: "disabled"
},
{
displayName: "Enabled",
value: "enabled"
}
]
};
}
onSelectOption = selected => {
this.props.onSelect(this.props.switchName, selected);
};
render() {
const { options } = this.state;
const { selected } = this.props;
return (
<MultiToggle
options={options}
selectedOption={selected}
onSelectOption={this.onSelectOption}
/>
);
}
}
Parent Setting
import MultiToggle from "react-multi-toggle";
import React from "react";
import "react-multi-toggle/style.css";
export default class ParentSwitch extends React.Component {
constructor(props) {
super(props);
this.state = {
options: [
{
displayName: "Disabled",
value: "disabled"
},
{
displayName: "Pending",
value: "pending"
},
{
displayName: "Enabled",
value: "enabled"
}
]
};
}
render() {
const { options } = this.state;
return (
<MultiToggle
options={options}
selectedOption={this.props.parentSwitch}
onSelectOption={() => {}}
/>
);
}
}
I will suggest that you group your child and parent under one component. Let say we name it Settings. Then, we create another component that will render a list of Settings and a button. This last component will hold the values of all Settings. Finally, each time the value of a Setting Component Change, we update the list. Checkout a sample working app here.
App Component
export default class App extends PureComponent {
state = {};
onSettingChange = (settingId, setting) => {
this.setState(prevState => ({
...prevState,
[settingId]: setting
}));
};
onGetSettingValues = () => {
console.log(this.state);
};
render() {
return (
<Fragment>
<Setting id="setting1" onChange={this.onSettingChange} />
<Setting id="setting2" onChange={this.onSettingChange} />
<button onClick={this.onGetSettingValues}>Get All Values</button>
</Fragment>
);
}
}
Setting Component
import React, { PureComponent, Fragment } from "react";
import ChildSwitch from "./ChildSwitch";
import ParentSwitch from "./ParentSwitch";
export default class Setting extends PureComponent {
state = {
parentVal: "disabled",
switch1Val: "enabled",
switch2Val: "disabled"
};
componentDidMount() {
this.setParentSwitchValue();
}
setChildSwitchValue = (whichSwitch, selected) => {
this.setState(
prevState => ({ ...prevState, [whichSwitch]: selected }),
this.setParentSwitchValue
);
};
handleChange = () => {
const { id, onChange } = this.props;
onChange(id, this.state);
};
setParentSwitchValue = () => {
const { switch1Val, switch2Val } = this.state;
const switchStates = [switch1Val, switch2Val];
let parent = "pending";
if (switchStates.every(val => val === "enabled")) {
parent = "enabled";
}
if (switchStates.every(val => val === "disabled")) {
parent = "disabled";
}
this.setState(
prevState => ({ ...prevState, parentVal: parent }),
this.handleChange
);
};
render() {
const { parentVal, switch1Val, switch2Val } = this.state;
return (
<Fragment>
<div className="boxed">
Parent Setting 1
<ParentSwitch
parentSwitch={parentVal}
onSelect={this.setParentSwitchValue}
/>
Setting 1:
<ChildSwitch
switchName={"switch1Val"}
selected={switch1Val}
onSelect={this.setChildSwitchValue}
/>
Setting 2:
<ChildSwitch
switchName={"switch2Val"}
selected={switch2Val}
onSelect={this.setChildSwitchValue}
/>
</div>
</Fragment>
);
}
}
Put all your states into a single context hook.
const SettingsContext = createContext({state1, state2/* all your states in here*/);
You'll then wrap the whole thing into this context as such:
<SettingsContext.Provider>
<App/>
</SettingsContext.Provider>
Now you can access the state in any of the children, parents etc. I suggest however not storing things like "disabled", "enabled" as strings, but rather store states as { enabled: true, pending: false}

How to target specific element after mapping and passing onClick function as props

I am facing such problem, i got my array of records fetched from an API, mapped it into single elements and outputting them as single components. I have function which changes state of parent Component, passes value to child component and child component should hide/show div content after button is clicked.
Of course. It is working, but partially - my all divs are being hidden/shown. I have set specific key to each child component but it doesn't work.
App.js
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import countries from '../../countriesList';
import CitySearchForm from './CitySearchForm/CitySearchForm';
import CityOutput from './CityOutput/CityOutput';
import ErrorMessage from './ErrorMessage/ErrorMessage';
class App extends Component {
state = {
country: '',
error: false,
cities: [],
infoMessage: '',
visible: false
}
getCities = (e) => {
e.preventDefault();
const countryName = e.target.elements.country.value.charAt(0).toUpperCase() + e.target.elements.country.value.slice(1);
const countryUrl = 'https://api.openaq.org/v1/countries';
const wikiUrl ='https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&explaintext&format=json&category=city&redirects&origin=*&titles=';
const allowedCountries = new RegExp(/spain|germany|poland|france/, 'i');
if (allowedCountries.test(countryName)) {
axios
.get(countryUrl)
.then( response => {
const country = response.data.results.find(el => el.name === countryName);
return axios.get(`https://api.openaq.org/v1/cities?country=${country.code}&order_by=count&sort=desc&limit=10`)
})
.then( response => {
const cities = response.data.results.map(record => {
return { name: record.city };
});
cities.forEach(city => {
axios
.get(wikiUrl + city.name)
.then( response => {
let id;
for (let key in response.data.query.pages) {
id = key;
}
const description = response.data.query.pages[id].extract;
this.setState(prevState => ({
cities: [...prevState.cities, {city: `${city.name}`, description}],
infoMessage: prevState.infoMessage = ''
}))
})
})
})
.catch(error => {
console.log('oopsie, something went wrong', error)
})
} else {
this.setState(prevState => ({
infoMessage: prevState.infoMessage = 'This is demo version of our application and is working only for Spain, Poland, Germany and France',
cities: [...prevState.cities = []]
}))
}
}
descriptionTogglerHandler = () => {
this.setState((prevState) => {
return { visible: !prevState.visible};
});
};
render () {
return (
<div className="App">
<ErrorMessage error={this.state.infoMessage}/>
<div className="form-wrapper">
<CitySearchForm getCities={this.getCities} getInformation={this.getInformation} countries={countries}/>
</div>
{this.state.cities.map(({ city, description }) => (
<CityOutput
key={city}
city={city}
description={description}
show={this.state.visible}
descriptionToggler={this.descriptionTogglerHandler} />
))}
</div>
);
}
}
export default App;
CityOutput.js
import React, { Component } from 'react';
import './CityOutput.css';
class CityOutput extends Component {
render() {
const { city, descriptionToggler, description, show } = this.props;
let descriptionClasses = 'output-record description'
if (show) {
descriptionClasses = 'output-record description open';
}
return (
<div className="output">
<div className="output-record"><b>City:</b> {city}</div>
<button onClick={descriptionToggler}>Read more</button>
<div className={descriptionClasses}>{description}</div>
</div>
)
}
};
export default CityOutput;
Put the visible key and the toggle function in the CityOutput instead of having it in the parent
import React, { Component } from "react";
import "./CityOutput.css";
class CityOutput extends Component {
state = {
visible: true
};
descriptionTogglerHandler = () => {
this.setState({ visible: !this.state.visible });
};
render() {
const { city, description } = this.props;
let descriptionClasses = "output-record description";
if (this.state.visible) {
descriptionClasses = "output-record description open";
}
return (
<div className="output">
<div className="output-record">
<b>City:</b> {city}
</div>
<button onClick={() => this.descriptionTogglerHandler()}>Read more</button>
<div className={descriptionClasses}>{description}</div>
</div>
);
}
}
export default CityOutput;
There are two ways of how I would approach this,
The first one is setting in your state a key property and check and compare that key with the child keys like:
state = {
country: '',
error: false,
cities: [],
infoMessage: '',
visible: false.
currKey: 0
}
descriptionTogglerHandler = (key) => {
this.setState((prevState) => {
return { currKey: key, visible: !prevState.visible};
});
};
// then in your child component
class CityOutput extends Component {
render() {
const { city, descriptionToggler, description, show, currKey, elKey } = this.props;
let descriptionClasses = 'output-record description'
if (show && elKey === currKey) {
descriptionClasses = 'output-record description open';
}
return (
<div className="output">
<div className="output-record"><b>City:</b> {city}</div>
<button onClick={() => descriptionToggler(elKey)}>Read more</button>
<div className={descriptionClasses}>{description}</div>
</div>
)
}
};
The other way is to set an isolated state for every child component
class CityOutput extends Component {
constructor(props) {
this.state = {
show: false
}
}
function descriptionToggler() {
const {show} = this.state;
this.setState({
show: !show
})
}
render() {
const { city, descriptionToggler, description } = this.props;
let descriptionClasses = 'output-record description'
if (this.state.show) {
descriptionClasses = 'output-record description open';
}
return (
<div className="output">
<div className="output-record"><b>City:</b> {city}</div>
<button onClick={descriptionToggler}>Read more</button>
<div className={descriptionClasses}>{description}</div>
</div>
)
}
};
I hope this helps ;)

Categories

Resources