how to use the componentDidMount in react JS

0

What I am trying to do is that this part

const topics = [
  {
    name: 'React Router',
    id: 'react-router',
    description: 'Declarative, component based routing for React',
    resources: [
      {
        name: 'URL Parameters',
        id: 'url-parameters',
        description: "URL parameters are parameters whose values are set dynamically in a page's URL. This allows a route to render the same component while passing that component the dynamic portion of the URL so it can change based off of it.",
        url: 'https://tylermcginnis.com/react-router-url-parameters'
      },
      {
        name: 'Programatically navigate',
        id: 'programmatically-navigate',
        description: "When building an app with React Router, eventually you'll run into the question of navigating programmatically. The goal of this post is to break down the correct approaches to programmatically navigating with React Router.",
        url: 'https://tylermcginnis.com/react-router-programmatically-navigate/'
      }
    ]
  },
  {
    name: 'React.js',
    id: 'reactjs',
    description: 'A JavaScript library for building user interfaces',
    resources: [
      {
        name: 'React Lifecycle Events',
        id: 'react-lifecycle',
        description: "React Lifecycle events allow you to tie into specific phases of a components lifecycle",
        url: 'https://tylermcginnis.com/an-introduction-to-life-cycle-events-in-react-js/'
      },
      {
        name: 'React AHA Moments',
        id: 'react-aha',
        description: "A collection of 'Aha' moments while learning React.",
        url: 'https://tylermcginnis.com/react-aha-moments/'
      }
    ]
  },
  {
    name: 'Functional Programming',
    id: 'functional-programming',
    description: 'In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.',
    resources: [
      {
        name: 'Imperative vs Declarative programming',
        id: 'imperative-declarative',
        description: 'A guide to understanding the difference between Imperative and Declarative programming.',
        url: 'https://tylermcginnis.com/imperative-vs-declarative-programming/'
      },
      {
        name: 'Building User Interfaces with Pure Functions and Function Composition',
        id: 'fn-composition',
        description: 'A guide to building UI with pure functions and function composition in React',
        url: 'https://tylermcginnis.com/building-user-interfaces-with-pure-functions-and-function-composition-in-react-js/'
      }
    ]
  }
]

I turned it into a JSON in another test project I did it this way

class App extends Component {
  state = {
    topics: []
  }
 
  async componentDidMount(){
    const topics = await (await fetch('http://localhost:4000/data')).json()
    console.log(topics)
    this.setState({ topics })
  }
  render() {
    const { topics } = this.state
    return (

but in the new test project I have developed everything by separate functions

import React, { Component } from 'react'
import {
  BrowserRouter as 
  Router,
  Route,
  Link,
} from 'react-router-dom'

const topics = [
  {
    name: 'React Router',
    id: 'react-router',
    description: 'Declarative, component based routing for React',
    resources: [
      {
        name: 'URL Parameters',
        id: 'url-parameters',
        description: "URL parameters are parameters whose values are set dynamically in a page's URL. This allows a route to render the same component while passing that component the dynamic portion of the URL so it can change based off of it.",
        url: 'https://tylermcginnis.com/react-router-url-parameters'
      },
      {
        name: 'Programatically navigate',
        id: 'programmatically-navigate',
        description: "When building an app with React Router, eventually you'll run into the question of navigating programmatically. The goal of this post is to break down the correct approaches to programmatically navigating with React Router.",
        url: 'https://tylermcginnis.com/react-router-programmatically-navigate/'
      }
    ]
  },
  {
    name: 'React.js',
    id: 'reactjs',
    description: 'A JavaScript library for building user interfaces',
    resources: [
      {
        name: 'React Lifecycle Events',
        id: 'react-lifecycle',
        description: "React Lifecycle events allow you to tie into specific phases of a components lifecycle",
        url: 'https://tylermcginnis.com/an-introduction-to-life-cycle-events-in-react-js/'
      },
      {
        name: 'React AHA Moments',
        id: 'react-aha',
        description: "A collection of 'Aha' moments while learning React.",
        url: 'https://tylermcginnis.com/react-aha-moments/'
      }
    ]
  },
  {
    name: 'Functional Programming',
    id: 'functional-programming',
    description: 'In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.',
    resources: [
      {
        name: 'Imperative vs Declarative programming',
        id: 'imperative-declarative',
        description: 'A guide to understanding the difference between Imperative and Declarative programming.',
        url: 'https://tylermcginnis.com/imperative-vs-declarative-programming/'
      },
      {
        name: 'Building User Interfaces with Pure Functions and Function Composition',
        id: 'fn-composition',
        description: 'A guide to building UI with pure functions and function composition in React',
        url: 'https://tylermcginnis.com/building-user-interfaces-with-pure-functions-and-function-composition-in-react-js/'
      }
    ]
  }
]

function Resource ({ match }) {
  const topic = topics.find(({ id }) => id === match.params.topicId)
    .resources.find(({ id }) => id === match.params.subId)

  return (
    <div>
      <h3>{topic.name}</h3>
      <p>{topic.description}</p>
      <a href={topic.url}>More info.</a>
    </div>
  )
}

function Topic ({ match }) {
  const topic = topics.find(({ id }) => id === match.params.topicId)

  return (
    <div>
      <h2>{topic.name}</h2>
      <p>{topic.description}</p>

      <ul>
        {topic.resources.map((sub) => (
          <li key={sub.id}>
            <Link to={'${match.url}/${sub.id}'}>{sub.name}</Link>
          </li>
        ))}
      </ul>

      <hr />

      <Route path={'${match.path}/:subId'} component={Resource} />
    </div>
  )
}

function Topics ({ match }) {
  return (
    <div>
      <h1>Topics</h1>
      <ul>
        {topics.map(({ name, id }) => (
          <li key={id}>
            <Link to={'${match.url}/${id}'}>{name}</Link>
          </li>
        ))}
      </ul>

      <hr />

      <Route path={'${match.path}/:topicId'} component={Topic}/>
    </div>
  )
}

function Home () {
  return (
    <h1>
      Home.
    </h1>
  )
}

class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          <ul>
            <li><Link to='/'>Home</Link></li>
            <li><Link to='/topics'>Topics</Link></li>
          </ul>

          <hr />

          <Route exact path='/' component={Home} />
          <Route path='/topics' component={Topics} />
        </div>
      </Router>
    )
  }
}

export default App

My question is how can I do so that I have the JSON through a link without having to write it directly in the code

I attach all the functional code thanks for the help.

    
asked by Francisco Navarrete 31.08.2018 в 17:02
source

2 answers

1

You could import the json file:

import myJsonDatae from './jsonData.json';

Where myJsonData.json is located on the same route and looks like this:

[
  {
    "name": "React Router",
    "id": "react-router",
    "description": "Declarative, component based routing for React",
    "resources": [
      {
        "name": "URL Parameters",
        "id": "url-parameters",
        "description": "URL parameters are parameters whose values are set dynamically in a page's URL. This allows a route to render the same component while passing that component the dynamic portion of the URL so it can change based off of it.",
        "url": "https://tylermcginnis.com/react-router-url-parameters"
      },
      {
        "name": "Programatically navigate",
        "id": "programmatically-navigate",
        "description": "When building an app with React Router, eventually you'll run into the question of navigating programmatically. The goal of this post is to break down the correct approaches to programmatically navigating with React Router.",
        "url": "https://tylermcginnis.com/react-router-programmatically-navigate/"
      }
    ]
  },
  {
    "name": "React.js",
    "id": "reactjs",
    "description": "A JavaScript library for building user interfaces",
    "resources": [
      {
        "name": "React Lifecycle Events",
        "id": "react-lifecycle",
        "description": "React Lifecycle events allow you to tie into specific phases of a components lifecycle",
        "url": "https://tylermcginnis.com/an-introduction-to-life-cycle-events-in-react-js/"
      },
      {
        "name": "React AHA Moments",
        "id": "react-aha",
        "description": "A collection of 'Aha' moments while learning React.",
        "url": "https://tylermcginnis.com/react-aha-moments/"
      }
    ]
  },
  {
    "name": "Functional Programming",
    "id": "functional-programming",
    "description": "In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.",
    "resources": [
      {
        "name": "Imperative vs Declarative programming",
        "id": "imperative-declarative",
        "description": "A guide to understanding the difference between Imperative and Declarative programming.",
        "url": "https://tylermcginnis.com/imperative-vs-declarative-programming/"
      },
      {
        "name": "Building User Interfaces with Pure Functions and Function Composition",
        "id": "fn-composition",
        "description": "A guide to building UI with pure functions and function composition in React",
        "url": "https://tylermcginnis.com/building-user-interfaces-with-pure-functions-and-function-composition-in-react-js/"
      }
    ]
  }
]

So when loading the component you can set the call to the ComponentDidMount method in the state.

componentDidMount() {
  this.setState({ data: myJsonData });
}
    
answered by 01.09.2018 / 12:51
source
0

what you can do, to keep the code more ordered is to create an api mock with your data, you can do it here: link .

Then, you can use axios, fetch, or super-agent to do the get (bring the information) like this:

componentDidMount() {
axios.get('https://'link generado aca'')
  .then(res => {
    const informacion = res.data;
    this.setState({ informacion });
  })

}

And with that I should be able to do it.

Also, to keep the code more structured, I could do a function that is in charge of calling the data. so componentDidMount, would only be responsible for setting the new state.

    
answered by 04.09.2018 в 04:45