Skip to content

Instantly share code, notes, and snippets.

@chengjieyun59
chengjieyun59 / FunctionalAstronaut.js
Last active March 18, 2023 17:33
Fetch from an endpoint in React functional component with hooks
import { useState, useEffect } from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const [astronauts, setAstronauts] = useState([]);
// setting the dependencies array in useEffect to an empty array
// ensures this fetch request only runs once instead of infinitely
useEffect(() => {
@chengjieyun59
chengjieyun59 / Astronaut.js
Created March 5, 2021 05:50
Fetch from an endpoint in React class component with state
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
// initialize the astronauts with an empty array
// to avoid running into null pointer exceptions
// after the first render, but before the componentDidMount() gets called