Unexpected token on line 17:115 reactjs - reactjs

The code runs perfectly fine when i run npm start. Website does get render on browser but it still shows an error in my terminal.
Line 17:115: Parsing error: Unexpected token, expected ";"
I already did a search related to this problem. The solution, I get from most of the website is that people forget to put componentDidMount in Class component but as you can seen in my code it already present in Class componenet.
import React from 'react';
import {
List
} from './CardList';
// import {Data} from './data';
import {
SearchBox
} from './SearchBox';
import './App.css'
export class Main extends React.Component {
constructor() {
super();
this.state = {
"Data": [],
"searchfield": ''
}
}
componentDidMount() {
LINE 17---> fetch('https://jsonplaceholder.typicode.com/users').then(Response => Response.json()).then(users => this.setState({Data: users}));
}
Searchchange = (event) => {
this.setState({
searchfield: event.target.value
});
}
render() {
const filterrobot = this.state.Data.filter(Data => {
return Data.name.toLowerCase().includes(this.state.searchfield.toLowerCase())
})
if (this.state.Data.length === 0) {
return <h1 className='tc'>Loagding</h1>
} else {
return (
<div className='tc'>
<h1 className='f1'>SEARCH PICTURES></h1>
<SearchBox secondchange = {this.Searchchange}/>
<List Data={filterrobot}/>
</div>
);
}
}
}

Related

React, How to use a menu in a seperate file to call an api and return data to a different section of the main file

I have a react app with a large menu, and as such am trying to move it to a seperate file from the main app.js
at the mement when you click on a link in the menu it call a node api and which returns some data, however when I try to seperate I can not get it to populate the results section which is still in the main script
Working version app.js
import React,{ useState } from 'react';
import './App.css';
import axios from 'axios';
import { Navigation } from "react-minimal-side-navigation";
import "react-minimal-side-navigation/lib/ReactMinimalSideNavigation.css";
export default class MyList extends React.Component {
constructor(props) {
super(props);
this.state = {
result: [],
};
this.callmyapi = this.callmyapi.bind(this);
}
render() {
return (
<div>
<div class="menu">
<Navigation
onSelect={({itemId}) => {
axios.get(`/api/menu/`, {
params: {
Menu: itemId,
}
})
.then(res => {
const results = res.data;
this.setState({ results });
})
.catch((err) => {
console.log(err);
})
}}
items={[
{
title: 'Pizza',
itemId: '/menu/Pizza/',
},
{
title: 'Cheese',
itemId: '/menu/cheese',
}
]}
/>
</div>
<div class="body">
this.state.results && this.state.results.map(results => <li>* {results.Name}</li>);
</div>
</div>
);
}
}
New app.js
import React,{ useState } from 'react';
import './App.css';
//import axios from 'axios';
//import { Navigation } from "react-minimal-side-navigation";
//import "react-minimal-side-navigation/lib/ReactMinimalSideNavigation.css";
import MyMenu from './mymenu';
export default class MyList extends React.Component {
constructor(props) {
super(props);
this.state = {
result: [],
};
this.callmyapi = this.callmyapi.bind(this);
}
render() {
return (
<div>
<div class="menu">
<MyMenu />
</div>
<div class="body">
this.state.results && this.state.results.map(results => <li>* {results.Name}</li>);
</div>
</div>
);
}
}
New menu file
mymenu.js
import React, { Component } from 'react';
import axios from 'axios';
import './App.css';
//import MyList from './App.js';
//import { ProSidebar, Menu, MenuItem, SubMenu } from 'react-pro-sidebar';
//import 'react-pro-sidebar/dist/css/styles.css';
import { Navigation } from "react-minimal-side-navigation";
//import Icon from "awesome-react-icons";
import "react-minimal-side-navigation/lib/ReactMinimalSideNavigation.css";
//export default async function MyMenu(){
export default class MyMenu extends React.Component {
constructor(props) {
super(props);
};
render() {
return (
<div>
<Navigation
// you can use your own router's api to get pathname
activeItemId="/management/members"
onSelect={({itemId}) => {
// return axios
axios.get(`/api/menu/`, {
params: {
// Menu: itemId,
Menu: "meat",
SubMenu : "burgers"
}
})
.then(res => {
const results = res.data;
this.setState({ results });
})
.catch((err) => {
console.log(err);
})
}}
items={[
{
title: 'Pizza',
itemId: '/menu/Pizza/',
},
{
title: 'Cheese',
itemId: '/menu/cheese',
}
]}
/>
</div>
);
}
}
Any help would be greatly appreciated
That one is quite easy once you understand state. State is component specific it that case. this.state refers to you App-Component and your Menu-Component individually. So in order for them to share one state you have to pass it down the component tree like this.
export default class MyList extends React.Component {
constructor(props) {
super(props);
this.state = {
result: [],
};
}
render() {
return (
<div>
<div class="menu">
<MyMenu handleStateChange={(results: any[]) => this.setState(results)} />
</div>
<div class="body">
this.state.results && this.state.results.map(results => <li>* {results.Name}</li>);
</div>
</div>
);
}
}
See this line: <MyMenu handleStateChange={(results: any[]) => this.setState(results)} />
There you pass a function to mutate the state of App-Component down to a the child
There you can call:
onSelect={({itemId}) => {
// return axios
axios.get(`/api/menu/`, {
params: {
// Menu: itemId,
Menu: "meat",
SubMenu : "burgers"
}
})
.then(res => {
const results = res.data;
this.props.handleStateChange(results)
})
.catch((err) => {
console.log(err);
})
You mutate the parent state and the correct data is being rendered. Make sure to practice state and how it works and how usefull patterns look like to share state between components.
Thanks - I Have found solution (also deleted link question)
above render added function
handleCallback = (results) =>{
this.setState({data: results})
}
then where I display the menu
<MyMenu parentCallback = {this.handleCallback}/>
where i display the results
{this.state.results && this.state.results.map(results => <li>{results.Name}</li>}
No aditional changes to the menu scripts

ReactJS -- Unable to find latest title from an api causing error

I have a Landing component and a NewsLatest component. I am hitting on an api and trying to find the article with the latest timestamp but iam unable to get it done in reactJS.I checked the js code its working fine but in react it is not rendering. Kindly suggest something.
import React, { Component } from 'react'
import NewsSearch from '../NewsSearch/NewsSearch';
import NewsLatest from '../NewsLatest/NewsLatest';
import './Landing.css';
import axios from 'axios';
class Landing extends Component {
state={
newsList: []
}
componentDidMount(){
axios.get(`https://api.nytimes.com/svc/topstories/v2/home.json?api-key=7cK9FpOnC3zgoboP2CPGR3FcznEaYCJv`)
.then(res=> {
this.setState({newsList: res.data.results});
});
}
render() {
// console.log(this.state.newsList);
return (
<div className="landing text-center text-white">
<h1>News Portal</h1>
<div className="news-search">
<NewsSearch />
</div>
<div className="news-latest">
<NewsLatest newsList={this.state.newsList}/>
</div>
</div>
)
}
}
export default Landing;
import React, { Component } from 'react';
// import PropTypes from 'prop-types';
class NewsLatest extends Component {
constructor(props){
super(props);
this.state = {
newsTitle:'',
abstract:'',
newsUrl:'',
}
// this.newsLatest = this.newsLatest.bind(this);
}
newsLatest = (e)=>{
// e.preventDefault();
const {newsList} = this.props;
let maxTime = newsList.map(function(o) {
return new Date(o.updated_date);
});
let maximumValue = Math.max(...maxTime);
let latestnews = newsList.filter(function (el) {
return maximumValue === new Date(el.updated_date).getTime();
})[0];
if(latestnews){
this.setState({newsTitle: latestnews.title});
return (<h4>{this.state.newsTitle}</h4>);
}
}
newsTitle = () => (
this.props.newsList.map(item => (<h2 key={item.title}>{item.title}</h2>))
)
render() {
console.log(this.props.newsList);
return (
<div>
<h2>News Latest....</h2>
{this.newsLatest()}
</div>
);
}
}
export default NewsLatest;
There is some issue in rendering in NewsLatest component. KIndly suggest something.
Try this:
You must probably be getting a maximum depth error, use a lifecycle method instead like componentDidUpdate. Update your component state only if the previous props are different from the newer ones.
Read more here: https://reactjs.org/docs/react-component.html
import React, { Component } from "react";
// import PropTypes from 'prop-types';
class NewsLatest extends Component {
constructor(props) {
super(props);
this.state = {
newsTitle: "",
abstract: "",
newsUrl: ""
};
// this.newsLatest = this.newsLatest.bind(this);
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.newsList !== this.props.newsList) {
const { newsList } = this.props;
let maxTime = newsList.map(function(o) {
return new Date(o.updated_date);
});
let maximumValue = Math.max(...maxTime);
let latestnews = newsList.filter(function(el) {
return maximumValue === new Date(el.updated_date).getTime();
})[0];
this.setState({ newsTitle: latestnews.title });
}
}
// newsLatest = e => {
// // e.preventDefault();
// const { newsList } = this.props;
// let maxTime = newsList.map(function(o) {
// return new Date(o.updated_date);
// });
// let maximumValue = Math.max(...maxTime);
// let latestnews = newsList.filter(function(el) {
// return maximumValue === new Date(el.updated_date).getTime();
// })[0];
// console.log(latestnews)
// if (latestnews && latestnews.hasOwnProperty('length') && latestnews.length>0) {
// return <h4>{this.state.newsTitle}</h4>;
// }
// };
newsTitle = () =>
this.props.newsList.map(item => <h2 key={item.title}>{item.title}</h2>);
render() {
console.log(this.props.newsList);
return (
<div>
<h2>News Latest....</h2>
<h4>{this.state.newsTitle}</h4>
</div>
);
}
}
export default NewsLatest;
Also, a sandbox: https://codesandbox.io/s/hungry-frog-z37y0?fontsize=14

How to test onclick api call with react

I have 3 react components and when the user clicks on USER_CARD in header then an api is called and the response is displayed in TwitterList component. I have no experience with unit testing, so what are the unit test needs to be done and how? I have read about enzyme and jest but not sure about the implementation.
Fews things I understand here that I need to test the click and also check if the api is responding with any data or not.
Please help me understand how to do this?
import React ,{Component}from 'react'
// Import all contianers here
import Header from './containers/header'
import TweetList from './containers/tweetlist'
// Import all services here
import Http from './services/http'
import './App.css'
class App extends Component {
constructor() {
super()
this.state = {
data: [],
isTop: true,
userName: ''
}
}
_getUserTweets = (user) => {
console.log(user)
if (user !== undefined && user !== '') {
Http.get('/' + user)
.then(response => {
if (response.data.length > 0) {
this.setState((prevState) => {
return {
...prevState,
data: response.data,
userName: user
}
})
}
})
.catch(error => {
console.log(error)
})
} else {
console.log('No user found!!')
}
}
render() {
const {data, userName} = this.state
return (
<div className="app_container">
<Header getUserTweets={this._getUserTweets} />
<TweetList data={data} user={userName} />
</div>
);
}
}
export default App;
import React, {Component} from 'react'
class TweetList extends Component {
constructor() {
super()
this.state = {
tweets: []
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.data.length > 0) {
this.setState((prevState) => {
return {
...prevState,
tweets: nextProps.data
}
})
}
}
render() {
const {tweets} = this.state
return (
<div>
{
tweets.length > 0
&&
tweets.map((currentValue, index) => {
return (
<p>{currentValue.full_text}</p>
)
})
}
</div>
)
}
}
export default TweetList
import React, {Component} from 'react'
import './style.css'
const USER_CARD = ({userName, onClickHandler}) => {
return (
<p onClick={() => onClickHandler(userName)}>{userName}</p>
)
}
class Header extends Component {
componentWillMount() {
if (process.env.REACT_APP_USER_LIST !== undefined && process.env.REACT_APP_USER_LIST.split(',').length > 0) {
this.props.getUserTweets(process.env.REACT_APP_USER_LIST.split(',')[0])
}
}
_getUserTweets = (userName) => {
this.props.getUserTweets(userName)
}
render() {
return(
<div className="header_container">
{process.env.REACT_APP_USER_LIST !== undefined
&&
process.env.REACT_APP_USER_LIST.split(',').length > 0
&&
process.env.REACT_APP_USER_LIST.split(',')
.map((currentValue, index) => {
return (
<USER_CARD userName={currentValue} key={`user-card-${index}`}
onClickHandler={this._getUserTweets} />
)
})}
</div>
)
}
}
export default Header
If the user click on the USER_CARD in Header component then we call an api to get the results.
What are the different unit testing that I can do and how to do it?
wrote this code by heart (so not tested) but should give you the idea:
unit test the onClick:
shallow the USER_CARD with enzyme like this, pass mock function, trigger click and check if the function was called with expected arguments:
const handlerMock = jest.fn()
const wrapper = shallow(<USER_CARD userName="foo" onClickHandler={handlerMock}/>)
wrapper.find('p').simulate('click') // or wrapper.find('p').prop('onClick)()
expect(handlerMock).toHaveBeenCalledTimes(1)
expect(handlerMock).toHaveBeenCalledWith("foo")
unit test the API
a) either mock the whole Http and then use mock return value, shallow your component and trigger your _getUserTweets like in 1. where I showed you how to test your onClick and then find your TweetList if data was set accordingly, here the mocking part of API:
import Http from './services/http'
jest.mock('./services/http')
const mockResponse = foobar; // response expected from your call
Http.get.mockReturnValue(({
then: (succ) => {
succ(mockResponse)
return ({
catch: jest.fn()
})
}
}))
b) dont mock Http but spyOn + mockImplementation:
const getSpy = jest.spyOn(Http, 'get').mockImplementation(() => ...) // here your mock implementation
important! restore at end of test:
getSpy.mockRestore()

How to access state values by index in React

I'm struggling to access values inside a state in React using axios and my code is as follows:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class App extends React.Component {
state = {
moviedata:null
}
getMovies(){
axios.get("http://127.0.0.1:8000/api/v1/movies/")
.then(moviedata => {
this.setState({
moviedata: moviedata.data
});
})
.then(x => { console.log(this.state.moviedata)});
}
componentDidMount(){
this.getMovies();
}
render () {
return <h1>Movie Examples include </h1>
}
}
ReactDOM.render(<App />, document.getElementById('react-app'));
The console.log looks like this:
0: {title: "Terminator 2: Judgement Day", plot: "Rise of the machines.", year: 1991}
1: {title: "The Italian Job", plot: "A comic hinging on a traffic jam", year: 1969}
How can I include the title of the first entry, i.e. 'Terminator 2: Judgement Day', inside the h1 tag, after the word 'include'?
I tried:
render () {
return <h1>Movie Examples include {this.state.moviedata[0].title}</h1>
}
and got an error TypeError: Cannot read property '0' of null
moviedata in your component state is initially null, so trying to access [0] from that will give rise to your error.
You could e.g. return early from the render method until moviedata has been set.
Example
class App extends React.Component {
// ...
render() {
const { moviedata } = this.state;
if (moviedata === null) {
return null;
}
return <h1>Movie Examples include {moviedata[0].title}</h1>;
}
}
You have to account for the fact that the Axios request is asynchronous, so the component may render before the data are loaded. For example:
render () {
const data = this.state.moviedata;
return <h1>Movie Examples include {data ? data[0].title : ""}</h1>
}
First, you have to "know" that the component is in a "loading" state. Without that, your state data is undefined (Still loading)
Here's how to do it:
class App extends React.Component {
state = {
moviedata:null,
isLoading: true
}
getMovies(){
axios.get("http://127.0.0.1:8000/api/v1/movies/")
.then(moviedata => {
this.setState({
moviedata: moviedata.data,
isLoading: false
});
})
.then(x => { console.log(this.state.moviedata)});
}
componentDidMount(){
this.getMovies();
}
render () {
if (this.state.isLoading) {
return <h1>Please wait...</h1>
}
// show only the first movie
return <h1>Movie #1 {this.state.moviedata[0].title}</h1>;
// show all the movies
return (
<>
{this.state.moviedata.map((m, idx) => <h1 key={idx}>Movie: {m.title}</h1>}
</>);
}
}

how can i create .env file in firebase for a react chat web app?

import React, { Component } from 'react';
import MessagePane from './MessagePane';
import ChannelList from './ChannelList';
import { getMessages, getChannels, saveMessage, onNewMessage } from './storage';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
messages: [],
channels: [],
selected_channel_id: null
};
this.onSendMessage = this.onSendMessage.bind(this);
this.onChannelSelect = this.onChannelSelect.bind(this);
}
componentDidMount() {
getMessages().then(messages => this.setState({messages}));
getChannels().then(channels => this.setState({channels, selected_channel_id: channels[0].id}));
onNewMessage(new_message => {
const messages = [...this.state.messages, new_message];
this.setState({messages});
});
}
onSendMessage(author, text) {
const new_message = {
id: this.state.messages[this.state.messages.length - 1].id + 1,
author,
text,
channel_id: this.state.selected_channel_id
};
saveMessage(new_message);
const messages = [...this.state.messages, new_message];
this.setState({messages});
}
onChannelSelect(id) {
this.setState({ selected_channel_id: id });
}
filteredMessages() {
return this.state.messages.filter(({channel_id}) => channel_id === this.state.selected_channel_id);
}
render() {
return (
<div className="App">
<ChannelList
channels={this.state.channels}
selectedChannelId={this.state.selected_channel_id}
onSelect={this.onChannelSelect}
/>
<MessagePane messages={this.filteredMessages()} onSendMessage={this.onSendMessage} />
</div>
);
}
}
export default App;
i do not know how to make constant in .env file for firebase. please help me if anyone know about this and how to connect and access firebase database for real time reload. i have also change the rules but it does not work for me.

Resources