React note #10

Yechan Jeon·2021년 12월 26일
0

React dev

목록 보기
10/18
post-thumbnail

Sending HTTP requests with react


First of all , you must not give direct access to database in broswer side.
The right order is React app <-> backend app <-> database.

Sending a get request

You can use browser built-in method 'fetch'

 async function fetchMovies() {
    try {
      const response = await fetch("https://swapi.dev/api/films");
      const data = await response.json();
      const transformedMovies = data.results.map((movieData) => {
        return {
          id: movieData["episode_id"],
          title: movieData.title,
          openingText: movieData["opening_crawl"],
          releaseDate: movieData["release_date"],
        };
      });
      setMovies(transformedMovies);
    } catch (error) {
      console.log(error);
    }
  }

Generating loading effect

Before we get a data from API or server, users doesn't know what's going on their browser if there is any instruction.
So set state for loading and generate it as to condition
const [isLoading, setIsLoading] = useState(false);

{!isLoading && movies.length > 0 && <MoviesList movies={movies} />}
{!isLoading && movies.length === 0 && <p>No movie found</p>}
{isLoading && <p>Loading...</p>}

Error handling

If you use axios package, axios will generate error automatically.
But Fetch doesn't work so.
const [error, setError] = useState(null);

try{
  .
  .
  setError(null);
  const response = await fetch("https://swapi.dev/api/films");
  if (response.status !== 200) {
    throw new Error("What the fuck you doing!");
  }
.
.
} catch (error) {
      setError(error.message);
}

fetch with useEffect()

Especially, When user loading the home page, home route definitely need some data from server.
Is this case, we can send request right away with useEffect as soon as user come into our web page.

useEffect(() => {
    fetchMovies();
  }, [fetchMovies]);

In this case, we execute fetchMovies at the first time and whenever fetchMovies function changed.
But if we use external state in fetchMovie func, we should wrap it with "useCallback()" to avoid infinite loop

Sending a post request to Firebase

Change method to 'POST'

async function addMovieHandler(movie) {
    try {
      const response = await fetch(
        "https://react-http-975ab-default-rtdb.firebaseio.com/movies.json",
        {
          method: "POST",
          body: JSON.stringify(movie),
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
      const data = await response.json();
      console.log(data);
    } catch (err) {
      console.log(err);
    }
  }
profile
방황했습니다. 다시 웹 개발 하려고요!

0개의 댓글