0

i am trying to get category_name of my project_category object from Axios request's response this is a single record so I am not mapping array its a whole object which stores in my state this is how i am trying to get that category name

const project=this.state.response; {project.project_category.category_name} 

here is image of my response

8
  • This should work fine. Please create a small demo for this using codesandbox.io to show the issue happening. Commented May 16, 2020 at 15:33
  • @palaѕн here is sample codesandbox.io/s/… Commented May 16, 2020 at 17:00
  • try this.state.response.data.project.project_category.category_name Commented May 16, 2020 at 17:07
  • @ertemishakk please check tha above sample link so you can understand this problem Commented May 16, 2020 at 17:10
  • what output are you expecting? a list or a specific line ? Commented May 16, 2020 at 17:13

2 Answers 2

2

The issue here is when the component is rendered initially then this.state.singleProject is just an empty object and you are trying to access data.address.street but this gives an error like:

Uncaught TypeError: Cannot read property 'street' of undefined

because data is an empty object initially.

To fix this issue you can simply use optional chaining operator ?. that permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

So, you can update your template like:

return ( <div className="App"> <h1>{data?.email}</h1> <h2>{data?.address?.street}</h2> </div> ); 

and your code will work fine after that.

Edit throbbing-dew-il5dr

Sign up to request clarification or add additional context in comments.

Comments

0
class App extends React.Component { constructor(props) { super(props); this.state = { data:[], singleProject: {}, errs: "" }; } componentDidMount() { Axios.get("https://jsonplaceholder.typicode.com/users") .then(res=>{ this.setState({ data:res.data }) }) } render() { const data = this.state.data; return ( <div className="App"> {data.map(eachData=>( <div key={eachData.id}> <h1>{eachData.email}</h1> <h2>{eachData.address.street}</h2> </div> ))} </div> ); } } export default App; 

1 Comment

yes you are right but in my scenario above answer works fine

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.