Syntax error: Unexpected token, expected , (24:2) - javascript

So I'm getting this error message saying that I have a syntax error on line 24. Which is the onSearchChange line.
Please someone help me, I've been stuck on this problem for over a day now.
import React, { Component } from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import './App.css';
class App extends Component {
constructor() {
super()
this.state = {
robots: [],
searchfield: ''
}
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response=> {
return response.json();
})
.then(users => {
this.setState({ robots: users})
}
onSearchChange = (event) => {
this.setState({ searchfield: event.target.value })
}
render() {
const filteredRobots = this.state.robots.filter(robots =>{
return robots.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
})
return (
<div className ='tc'>
<h1 className='f1'> RoboFriends</h1>
<SearchBox searchChange={this.onSearchChange}/>
<CardList robots={filteredRobots} />
</div>
);
}
}
export default App;

Your render function is inside componentDiDMount. Check for the opening and closing braces.

Related

searchChange is not defined no-undef

SearchBox.js File is:
import React from 'react';
const SearchBox = ({ searchfield, searchChanger}) => {
return (
<div className='pa2'>
<input
className='pa3 b--green bg-light-blue'
type='search'
placeholder='search robots'
onChange={searchChange}
/>
</div>
);
}
export default SearchBox;
App.js File is:
import React, { Component } from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import { robots } from './robots';
import './App.css';
class App extends Component {
constructor() {
super()
this.state = {
robots: robots,
searchfield:''
}
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => {this.setState({ robots: robots})});
}
onSearchChange = (event) => {
this.setState({ searchfield: event.target.value })
}
render() {
const filteredRobots = this.state.robots.filter(robots => {
return robots.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
})
if (robots.length ===0) {
return <h1>Loading</h1>
}
else {
return (
<div className='tc'>
<h1 className='f1'>RoboFriends</h1>
<SearchBox searchChange={this.onSearchChange}/>
<CardList robots={filteredRobots} />
</div>
);
}
}
}
export default App;
I was able to get rid of this error just by changing the order of import in App.js file, but later on its showing this error no matter what i do?
please help in case I have any typing issue, if no then what is the problem
Your SearchBox should be:
const SearchBox = ({ searchfield, searchChange}) => {
return (
<div className='pa2'>
<input
className='pa3 b--green bg-light-blue'
type='search'
placeholder='search robots'
onChange={searchChange}
/>
</div>
);
}
export default SearchBox;
In your props there was searchChanger which is incorrect.

Fetching data from api in componentDidMount is returning null

I am trying to fetch data in componentDidMount lifecycle method of react but I am not getting it.
my method is:
componentDidMount() {
const { taskId } = this.props
getTask(taskId)
.then(data => {
console.log(data);
this.setState({task: data});
})
}
my api is:
export const getTask = (unique_id) => {
console.log(unique_id)
return fetch('https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/'+ unique_id).then(res => {
return res.json();
});
};
this is my whole component:
import React, { Component } from 'react'
import { getTask } from '../../modules/clients';
import ClientTaskShow from '../../components/tasks/ClientTaskShow'
class ClientTaskShowContainer extends Component {
constructor(props) {
super(props)
this.state = {
messageModalOpen: false,
selectedPartnerId: null,
task:{}
}
}
componentDidMount() {
console.log("hello")
const { taskId } = this.props
getTask(taskId)
.then(data => {
console.log(data);
this.setState({task: data});
})
}
render() {
const taskSelected = this.state.task;
console.log(taskSelected)
return (
<ClientTaskShow
task={taskSelected}
/>
)
}
}
export default ClientTaskShowContainer;
code from where calling clienttaskShowContainer:
import React from 'react'
import Head from 'next/head'
import Layout from '../../components/Layout'
import ClientTaskShowContainer from '../../containers/tasks/ClientTaskShowContainer'
import requireAuth from '../../lib/requireAuth'
const ClientTasksShow = ({ query }) => {
const { taskId } = query
return (
<Layout fluid fullHeight clientTaskHeader='true'>
<Head>
<title>Client Task Details | Punctual</title>
</Head>
<ClientTaskShowContainer taskId={taskId} />
</Layout>
)
}
ClientTasksShow.getInitialProps = async ({ query }) => ({
query
})
export default requireAuth(ClientTasksShow)
I think its not hitting the API even. Although it hit once I restart the server but not again. I am not able to replicate the problem.
At some sites I found we should use .then for API call others says we can't pass perimeter in API call in componentDidMount. What is the exact solution for this. Please help. Thanks in advance.
This code is working
//Calling component
import React from "react";
import CallComp from "./CallComp";
import ReactDOM from "react-dom";
function App() {
return (
<div className="App">
<CallComp taskId={"7693fbf81a33"} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
// Child Component
import React, { Component } from "react";
import ClientTaskShow from "./ClientTaskShow";
class ClientTaskShowContainer extends Component {
constructor(props) {
super(props);
this.state = {
task: {}
};
}
componentDidMount() {
const { taskId } = this.props;
fetch(
`https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/${taskId}`
)
.then(response => response.json())
.then(data => this.setState({ task: data }))
.catch(error => console.log("the error is", error));
}
render() {
const taskSelected = this.state.task;
console.log("task selected is ", taskSelected);
return (
<div>
{Object.keys(taskSelected).length ? (
<ClientTaskShow task={taskSelected} />
) : (
<div>No data to show</div>
)}
</div>
);
}
}
export default ClientTaskShowContainer;
// Demo ClientTaskShow
import React from "react";
const ClientTaskShow = ({ task }) => {
return <h1>{task.unique_code}</h1>;
};
export default ClientTaskShow;
Actually its working
console.log(data) returns error message from api
You should return promise from function to know api request is resolved or not
try this:
export const getTask = (id) => {
return new Promise(function (resolve, reject) {
fetch('https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/' + id).then((res) => {
resolve(res.json())
})
});
}
And call like this:
componentDidMount() {
getTask(1).then((data)=>{
console.log(data);
});
}
You can replace params with your id
Hope this helps.

Render whole html file in react component

I am serving some content from my API.
I want display response from API in my react component.
Response is html with bundled all assets inline by webpack.
How can I do it?
I tried dangerouslySetInnerHTML but it crashes my javascript inside returned html.
My cmp :
import React, { Component } from 'react';
import axios from 'axios';
export default class Report extends Component {
constructor() {
super();
this.state = {
id: null,
report: null
};
}
getParam(param){
return new URLSearchParams(window.location.search).get(param);
}
componentWillMount() {
axios.post(`/url`,
{
'id': this.getParam('id'),
}
)
.then(res => {
this.setState({id: res.data});
setTimeout(() => {
axios.get(`https://rg.ovh/`+this.state.id)
.then(res => {
this.setState({report: res.data})
});
}, 1900);
});
}
render() {
return (
<div dangerouslySetInnerHTML={ {__html: this.state.report} } />
);
}
}
import axios from 'axios';
import React, { Component } from 'react';
import renderHTML from 'react-render-html';
class App extends Component {
constructor() {
super();
this.state = {
htmlString: ''
};
}
componentDidMount() {
axios.get('http://localhost:5000').then(response => {
this.setState({ htmlString: response.data })
}).catch(err => {
console.warn(err);
});
}
render() {
const { htmlString } = this.state;
return (
<div className="App">
{renderHTML(htmlString)}
</div>
);
}
}
export default App;

Unable to fetch data and React is not giving any error messages

I have this component:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { translate } from 'react-i18next';
const API = `http://accountmanagement.ng.bluemix.net/v1/accounts/${accountGuid}/traits`;
class GetMFAValidation extends Component {
constructor(props) {
super(props);
this.state = { data: '' };
}
render() {
return (
<div>
<p>HOLA, I AM ${accountGuid}</p>
</div>
);
}
componentDidMount() {
fetch(API).then(response => response.json()).then(data => {
console.log('data -->', data);
this.setState({ data });
});
}
}
GetMFAValidation.propTypes = {
accountGuid: PropTypes.string.isRequired,
};
export default compose(
connect(
store => ({ accountGuid: store.global.accountGuid }),
translate(),
),
)(GetMFAValidation);
And I am calling it in another component like:
import GetMFAValidation from "../path"
And <GetMFAValidation />
The app crashes but I am not receiving any errors.
Your API string has a variable in it:
const API = `http://accountmanagement.ng.bluemix.net/v1/accounts/${accountGuid}/traits`;
...but accountGuid is not accessible here.
You could use a function instead:
const getAPIUrl = (accountGuid) =>
`http://accountmanagement.ng.bluemix.net/v1/accounts/${accountGuid}/traits`;
And then pass in the accountGuid from props when used:
componentDidMount() {
const APIUrl = getAPIUrl(this.props.accountGuid)
fetch(APIUrl).then(response => response.json()).then(data => {
console.log('data -->', data);
this.setState({ data });
});
}
I hope this helps.
in your fetch methode, try to add a catch after then, and print the error, if it is because of the fetch, your program will still work, and you will get the error
fetch(API).then(response => response.json()).then(data => {
console.log('data -->', data);
this.setState({ data });
})
.catch(error => console.log(error));

object can't get method or property 'getCars'

i'm working on react-redux intermidiate..but i don't know what's going wrong
on this project
hera i have creacted the searchbar for getting car details..and the file is created as 'search.js'...you can see here..
search.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getCars } from '../actions';
import { bindActionCreators } from 'redux';
class Search extends Component{
constructor(props){
super(props);
this.state = {
keyword:''
}
}
searchCars = (event) => {
event.preventDefault();
this.props.getCars(this.state.keyword)
}
handleChange = (event) => {
this.setState({
keyword:event.target.value
})
}
componentDidMount(){
console.log(this.state);
}
render(){
return(
<div className="main_search">
<form onSubmit={this.searchCars}>
<input type="text" value={this.state.keyword} onChange = {this.handleChange} />
</form>
</div>
)
}
}
// mapStateToProps
// mapDispatchToProps
function mapDispatchToProps(dispatch){
return bindActionCreators({getCars}, dispatch)
}
export default connect(null,mapDispatchToProps)(Search);
and i think error comes from here about getCars..which is described below as s 'index.js'...you can see here
index.js
const URL_ROOT = 'http://localhost:3004'
export default function getCars(keywords){
const request = fetch(`${URL_ROOT}/carsIndex?q=${keywords}`,
{method:'GET'})
.then(response => response.json())
return{
type:'SEARCH_CARS',
payload:request
}
}
and the error looks like this..
and error showing in bundle.js file
so try to fix it and help me...
Please change your mapDispatchToProps method as
const mapDispatchToProps = (dispatch)=> (
bindActionCreators(getCars, dispatch)
)

Categories

Resources