adding data to a dictionary in react - javascript

I am using mqtt to receive some data and I would like to add that data directly to a dictionary.
My probably naive way to add the data to the dictionary is the following:
this.client.on('message', (topic, message) => {
this.state.mqttMessage[topic] = message.toString();
})
I also tried the following:
this.setState(prevState => ({
mqttMessage: {
...prevState.mqttMessage,
topic: message.toString()
}
}))
But that adds the keyword "topic" to the dictionary.
The above line seems to generate the following warning as well:
Do not mutate state directly. Use setState() react/no-direct-mutation-state
Later I would like to show what was received above, using this code:
render() {
console.log(this.props.mqttMessage)
return (
<div>
test1: {this.props.mqttMessage["test1"]} <br/>
test2: {this.props.mqttMessage["test2"]} <br/>
test3: {this.props.mqttMessage["test3"]} <br/>
</div>
);
}
But the problem is that objects don't seem to get updated directly, I need ti refresh the page in order for the content to kick in.
I guess I am not using the setState properly.
The proper way of doing what I am trying to do would be appreciated.
Below is the whole code:
import React, { Component } from 'react';
import Button from 'react-bootstrap/lib/Button';
import Tab from 'react-bootstrap/lib/Tab';
import Tabs from 'react-bootstrap/lib/Tabs';
import 'rc-slider/assets/index.css';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
mqttMessage: {}
}
this.mqtt = require('mqtt')
this.client = this.mqtt.connect('mqtt://192.168.10.100:9001')
this.client.on('connect', () => {
this.client.subscribe('test1')
this.client.subscribe('test2')
this.client.subscribe('test3')
})
this.client.on('message', (topic, message) => {
this.state.mqttMessage[topic] = message.toString();
})
}
render() {
return (
<div className="App">
<Tabs defaultActiveKey="profile" id="uncontrolled-tab-example">
<Tab eventKey="home" title="Home">
<PostMessage client={this.client} />
</Tab>
<Tab eventKey="seats" title="Seats">
<SeatPage mqttMessage={this.state.mqttMessage} client={this.client} />
</Tab>
</Tabs>
</div>
);
}
}
class PostMessage extends React.Component {
sendMessage = (e) => {
e.preventDefault();
this.props.client.publish('demo/test', 'My Message');
}
render() {
return (
<Button onClick={this.sendMessage}>
Send Message
</Button>
);
}
}
class SeatPage extends React.Component {
sendMessage = (e, topic, message) => {
e.preventDefault();
this.props.client.publish(topic, message);
}
render() {
console.log(this.props.mqttMessage)
return (
<div>
test1: {this.props.mqttMessage["test1"]} <br/>
test2: {this.props.mqttMessage["test2"]} <br/>
test3: {this.props.mqttMessage["test3"]} <br/>
</div>
);
}
}
export default () => (
<App />
);

In react you shouldn't change state object directly. You should rather use setState method.
Something like below should do the trick.
this.client.on('message', (topic, message) => {
this.setState({
...this.state,
mqttMessage: {
...this.state.mqttMessage,
[topic]: message
}
})
})

Related

How to pass props through Link method in React?

I am trying to pass a prop from one component in which I search for and select a game to another component where I will render the details of the selected game. I am keeping my components as two separate pages, but I am struggling to get anything passing down to the child component. Here are my two files, and I have no idea where I am going wrong.
import React, { Component } from "react";
import Selected from "./Selected";
import { Link } from 'react-router-dom';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
/*
API request format:
GET https://api.rawg.io/api/platforms?key=YOUR_API_KEY
GET https://api.rawg.io/api/games?key=YOUR_API_KEY&dates=2019-09-01,2019-09-30&platforms=18,1,7
Docs: https://api.rawg.io/docs
*/
baseURL: "https://api.rawg.io/api/games?",
apiKey: `key=${process.env.REACT_APP_RAWG_API_KEY}&`,
gamesQuery: "search=",
searchInput: "",
// later on we can determine whether to add additional parameters like page size, genres, etc.
searchURL: "",
gallery : [],
selectedGame: [],
};
}
handleChange = (event) => {
this.setState({
// we're grabbing the element or elements and dynamically setting the input value to the key corresponding to the input id of the same name in this.state
[event.target.id]: event.target.value,
});
};
handleSubmit = (event) => {
// keep the page from refreshing on submit
event.preventDefault();
this.setState(
{
// builds out our search url from the pieces we've assembled
searchURL:
this.state.baseURL +
this.state.apiKey +
this.state.gamesQuery +
this.state.searchInput,
},
() => {
// we fetch the url from the api
fetch(this.state.searchURL)
// .then waits till the fetch is complete
.then((response) => {
return response.json();
})
.then(
(json) => this.setState({
gallery : json.results
}),
(err) => console.log(err)
);
}
);
};
handleInspect = (event) => {
for (let i in this.state.gallery) {
if (i.id === event.id) {
this.setState ({
selectedGame : i
})
}
}
}
render() {
let game;
if (this.state.selectedGame) {
game = this.state.selectedGame
}
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>Search</label>
<input
id="searchInput"
type="text"
placeholder="What's the Name of the Game"
value={this.state.searchInput}
onChange={this.handleChange}
/>
<input type="submit" value="Find Games" />
</form>
<div id='gallery'>
{this.state.gallery.map(function(d, idx){
return (
<li key={idx}>
<a href={"/selected/"+d.id}
onClick={()=>this.handleInspect(d.id)}
>{d.name}</a>,
{d.id},
<Link to={{pathname: `/selected/${d.id}`,
gameResults : game}} />,
</li>)})}
</div>
</div>
);
}
}
export default Search;
And the component I try to pass to and fails.
import React from 'react';
import { Link } from 'react-router-dom';
class Selected extends React.Component {
render() {
{console.log(this.props)}
return (
<h1>woo</h1>
);
}};
export default Selected;
The result is below, with no props having been passed at all

React issue with rendering data from firebase

Basically I have an issue with rendering information got from firebase to the screen.
When I'm trying to call the function which gets the information from the database inside componentDidMount(), the function is not even executed, but when I call it inside the render() function, which I know it's now the right thing to do it works, it goes into an infinite loop and it keeps accessing the database over and over again, but it renders the correct information to the screen. So the function itself is not the issue, I guess, since it is able to retrieve the information from the database.
Also a console.log() inside the componentDidMount() seems to work so componentDidMount() does fire.
So how should I go forward with this issue? I've been struggling with this for several hours now. I can't seem to find the issue.
This is my code:
export default class Cars extends Component {
constructor(){
super();
this.state = {
cars: []
}
}
componentDidMount(){
this.loadCarsFromDB();
}
loadCarsFromDB = () => (
<FirebaseContext.Consumer>
{firebase => {
firebase.accessFirebase("cars").get()
.then(snapshot => {
let cars = [];
snapshot.docs.forEach(doc => {
cars.push(doc.data());
})
return cars;
})
.then(cars => {
this.setState({cars: cars});
})
.catch(err => {
console.log(err);
});
}
}
</FirebaseContext.Consumer>
)
renderCars = () => {
return this.state.cars.map(car => <Car
brandName={car.brandName}
model={car.model}
color={car.color}
price={car.price} />)
}
render() {
return (
<div className="car-item">
{this.renderCars()}
</div>
);
}
}
Firebase class except the credentials
export default class Firebase {
constructor() {
app.initializeApp(config);
}
accessFirebase = () => {
let db = app.firestore();
return db.collection("cars");
}
}
This is the Car function
const car = (props) => (
<div className="Car">
<span>{props.brandName ? props.brandName : "Nu exista"}</span>
<span>{props.model ? props.model : "Nu exista"}</span>
<span>{props.color ? props.color : "Nu exista"}</span>
<span>{props.price ? props.price : "Nu exista"}</span>
</div>
)
export default car;
And this is the index.js file. I don't know, maybe it has something to do with the use of contexts. I basically create only one firebase instance which should allow me to query the database from anywhere in the code by using only this very instance.
ReactDOM.render(
<FirebaseContext.Provider value={new Firebase()}>
<App />
</FirebaseContext.Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
App.jsx file
class App extends Component {
render(){
return(
<div>
<Cars/>
</div>
)
}
}
export default App;
You are not supposed to use the FirebaseContext.Consumer component from loadCarsFromDB. So I would lift up FirebaseContext.Consumer around Cars and pass down the firebase property as a prop.
class App extends Component {
render(){
return(
<div>
<FirebaseContext.Consumer>
{firebase => (
<Cars firebase={firebase}/>
)
}
<FirebaseContext.Consumer />
</div>
)
}
}
loadCarsFromDB = () => (
this.props.firebase.accessFirebase("cars").get()
.then(snapshot => {
let cars = [];
snapshot.docs.forEach(doc => {
cars.push(doc.data());
})
return cars;
})
.then(cars => {
this.setState({cars: cars});
})
.catch(err => {
console.log(err);
});
)

How to apply load more button to push this.state in React

The purpose of implementing <a className="button" onClick={this.loadMore}>Load more news</a> button is to take more objects with API and show without refresh the page. Still not sure the way to implementing setState method is ideal or not
this.setState({
newsData: [...this.state.newsData, ...responseJson]
})
App.js
import React from 'react';
import { Newslist } from './newslist/Newslist';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
page: 1,
newsData: ''
}
}
componentDidMount() {
this.page = 1;
this.requestNews();
}
requestNews () {
console.log('koooy');
fetch('http://localhost:3000/api/?page='+this.page)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
newsData: [...this.state.newsData, ...responseJson]
})
})
.catch((error) => {
console.error(error);
});
}
loadMore = () => {
this.requestNews();
}
render() {
return (
<main className="main">
<h1>Hello mate !</h1>
<Paggination />
{ this.state.newsData.length
? <Newslist currentNews={this.state.newsData} loadMoreData={this.loadMore} />
: <p>Loading...</p>
}
</main>
);
}
}
export default App;
Newslist.js
import React from 'react';
export class Newslist extends React.Component {
loadMore = () => {
event.preventDefault();
this.props.loadMoreData();
}
render () {
const newsInList = this.props.currentNews.map(newsDetails => {
return (
<section className="media" key={newsDetails.id}>
{newsDetails.image && <figure className="media-figure">
<img src={newsDetails.image} />
</figure>}
<div className="media-body">
<h3 className="media-title">{newsDetails.header}</h3>
<p>{newsDetails.content}</p>
</div>
</section>
);
});
return (
<div>
{newsInList}
<a className="button" onClick={this.loadMore}>Load more news</a>
</div>
);
}
}
What you have done seems reasonable. Basically, make sure you know your current news page/offset. When you make the API request, send the page/offset with the request and append the new use to the head or tail of the array.
I noticed a suggestion about the usage of Redux, Redux is rather complicated and this is a very simple issue, no need for it here.

Handling event on array item won't work - ReactJS

I try to map an array and put click event on the array items. I know it's a bit different because of how JavaScript handles functions but I can't make it work. I get the error: Cannot read property 'saveInStorage' of undefined. Can anyone tell me what I'm doing wrong? Thanks in advance! Here is my code:
import React from "react";
const data = require('../data.json');
export default class Gebruikers extends React.Component {
constructor() {
super();
this.state = {
users: data.users
};
this.saveInStorage = this.saveInStorage.bind(this)
}
saveInStorage(e){
console.log("test");
}
renderUser(user, i) {
return(
<p key={i} onClick={this.saveInStorage(user)}>f</p>
);
}
render() {
return (
<div>
{
this.state.users.map(this.renderUser)
}
</div>
);
}
}
this is undefined in renderUser()
You need to bind this for renderUser() in your constructor.
Also, you are calling saveInStorage() every time the component is rendered, not just onClick, so you'll need to use an arrow function in renderUser
import React from "react";
const data = require('../data.json');
export default class Gebruikers extends React.Component {
constructor() {
super();
this.state = {
users: data.users
};
this.saveInStorage = this.saveInStorage.bind(this);
this.renderUser = this.renderUser.bind(this);
}
saveInStorage(e){
console.log("test");
}
renderUser(user, i) {
return(
<p key={i} onClick={() => this.saveInStorage(user)}>
);
}
render() {
return (
<div>
{
this.state.users.map(this.renderUser)
}
</div>
);
}
}
Instead of binding you can also use an arrow function (per mersocarlin's answer). The only reason an arrow function will also work is because "An arrow function does not have its own this; the this value of the enclosing execution context is used" (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). The enclosing execution in your case is your render, where this is defined.
You need to make two changes to your code which are outlined below.
You are invoking the function when the component is rendered. To fix this update this line to the following
<p key={i} onClick={() => this.saveInStorage(user)}>
This means that the function will only be invoked when you click on the item.
You also need to bind the renderUser in your constructor or else use an arrow function.
this.renderUser = this.renderUser.bind(this);
See working example here.
Your onClick event handler is wrong.
Simply change it to:
onClick={() => this.saveInStorage(user)}
Don't forget to also bind renderUser in your constructor.
Alternatively, you can choose arrow function approach as they work the same as with bind:
class Gebruikers extends React.Component {
constructor(props) {
super(props)
this.state = {
users: [{ id: 1, name: 'user1' }, { id: 2, name: 'user2' }],
}
}
saveInStorage = (e) => {
alert("test")
}
renderUser = (user, i) => {
return(
<p key={i} onClick={() => this.saveInStorage(user)}>
{user.name}
</p>
)
}
render() {
return (
<div>{this.state.users.map(this.renderUser)}</div>
);
}
}
ReactDOM.render(
<Gebruikers />,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Paul Fitzgeralds answer is the correct one, although I'd like to propose a different way of handling this, without all the binding issues.
import React from "react";
const data = require('../data.json');
export default class Gebruikers extends React.Component {
constructor() {
super();
this.state = {
users: data.users
};
}
saveInStorage = (e) => {
console.log("test");
};
render() {
return (
<div>
{this.state.users.map((user, i) => {
return (<p key={i} onClick={() => this.saveInStorage(user)}>f</p>);
})}
</div>
);
}
}
With saveInStorage = (e) => {}; you are binding the saveInStorage function to the this context of your class. When invoking saveInStorage you'll always have the (at least I guess so in this case) desired this context.
The renderUser function is basically redundant. If you return one line of JSX, you can easily do this inside your render function. I think it improves readability, since all your JSX is in one function.
You are not sending the parameters to this.renderUser
this.state.users.map((user, i) => this.renderUser(user, i))
Also your onClick function should be slightly changed. Here's the full code changed:
import React from "react";
const data = require('../data.json');
export default class Gebruikers extends React.Component {
constructor() {
super();
this.state = {
users: data.users
};
this.saveInStorage = this.saveInStorage.bind(this)
}
saveInStorage(e){
console.log("test");
}
renderUser(user, i) {
return(
<p key={i} onClick={() => this.saveInStorage(user)}>f</p>
);
}
render() {
return (
<div>
{
this.state.users.map((user, i) => this.renderUser(user, i))
}
</div>
);
}
}

Unmount component on click in child component button // React

I am struggling with successfully removing component on clicking in button. I found similar topics on the internet however, most of them describe how to do it if everything is rendered in the same component. In my case I fire the function to delete in the child component and pass this information to parent so the state can be changed. However I have no idea how to lift up the index of particular component and this is causing a problem - I believe.
There is a code
PARENT COMPONENT
export class BroadcastForm extends React.Component {
constructor (props) {
super(props)
this.state = {
numberOfComponents: [],
textMessage: ''
}
this.UnmountComponent = this.UnmountComponent.bind(this)
this.MountComponent = this.MountComponent.bind(this)
this.handleTextChange = this.handleTextChange.bind(this)
}
MountComponent () {
const numberOfComponents = this.state.numberOfComponents
this.setState({
numberOfComponents: numberOfComponents.concat(
<BroadcastTextMessageForm key={numberOfComponents.length} selectedFanpage={this.props.selectedFanpage}
components={this.state.numberOfComponents}
onTextChange={this.handleTextChange} dismissComponent={this.UnmountComponent} />)
})
}
UnmountComponent (index) {
this.setState({
numberOfComponents: this.state.numberOfComponents.filter(function (e, i) {
return i !== index
})
})
}
handleTextChange (textMessage) {
this.setState({textMessage})
}
render () {
console.log(this.state)
let components = this.state.numberOfComponents
for (let i = 0; i < components; i++) {
components.push(<BroadcastTextMessageForm key={i} />)
}
return (
<div>
<BroadcastPreferencesForm selectedFanpage={this.props.selectedFanpage}
addComponent={this.MountComponent}
textMessage={this.state.textMessage} />
{this.state.numberOfComponents.map(function (component) {
return component
})}
</div>
)
}
}
export default withRouter(createContainer(props => ({
...props
}), BroadcastForm))
CHILD COMPONENT
import React from 'react'
import { createContainer } from 'react-meteor-data'
import { withRouter } from 'react-router'
import { BroadcastFormSceleton } from './BroadcastForm'
import './BroadcastTextMessageForm.scss'
export class BroadcastTextMessageForm extends React.Component {
constructor (props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.unmountComponent = this.unmountComponent.bind(this)
}
handleChange (e) {
this.props.onTextChange(e.target.value)
}
unmountComponent (id) {
this.props.dismissComponent(id)
}
render () {
console.log(this.props, this.state)
const textMessage = this.props.textMessage
return (
<BroadcastFormSceleton>
<div className='textarea-container p-3'>
<textarea id='broadcast-message' className='form-control' value={textMessage}
onChange={this.handleChange} />
</div>
<div className='float-right'>
<button type='button'
onClick={this.unmountComponent}
className='btn btn-danger btn-outline-danger button-danger btn-small mr-3 mt-3'>
DELETE
</button>
</div>
</BroadcastFormSceleton>
)
}
}
export default withRouter(createContainer(props => ({
...props
}), BroadcastTextMessageForm))
I am having problem with access correct component and delete it by changing state. Any thoughts how to achieve it?
Please fix the following issues in your code.
Do not mutate the state of the component. Use setState to immutably change the state.
Do not use array index as the key for your component. Try to use an id field which is unique for the component. This will also help with identifying the component that you would need to unmount.
Try something like this. As mentioned before, you don't want to use array index as the key.
class ParentComponent extends React.Component {
constructor() {
this.state = {
// keep your data in state, as a plain object
textMessages: [
{
message: 'hello',
id: '2342334',
},
{
message: 'goodbye!',
id: '1254534',
},
]
};
this.handleDeleteMessage = this.handleDeleteMessage.bind(this);
}
handleDeleteMessage(messageId) {
// filter by Id, not index
this.setState({
textMessages: this.state.textMessages.filter(message => message.id !== messageId)
})
}
render() {
return (
<div>
{this.state.textMessages.map(message => (
// Use id for key. If your data doesn't come with unique ids, generate them.
<ChildComponent
key={message.id}
message={message}
handleDeleteMessage={this.handleDeleteMessage}
/>
))}
</div>
)
}
}
function ChildComponent({message, handleDeleteMessage}) {
function handleClick() {
handleDeleteMessage(message.id)
}
return (
<div>
{message.message}
<button
onClick={handleClick}
>
Delete
</button>
</div>
);
}

Categories