投稿時間:2023-05-05 16:12:16 RSSフィード2023-05-05 16:00 分まとめ(12件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
python Pythonタグが付けられた新着投稿 - Qiita Python notebook - May https://qiita.com/AnyaQuantseng2/items/5bb339c8d1a7248515ab after 2023-05-05 15:49:36
python Pythonタグが付けられた新着投稿 - Qiita pythonでGoogle Drive API を使用した文字認識をする。 https://qiita.com/yutaka_m/items/32b50ec5b944ea1cbddf googledriveapi 2023-05-05 15:46:25
js JavaScriptタグが付けられた新着投稿 - Qiita 【Vue.js】Vue2→Vue3 主な記述方法の変更点 チートシート https://qiita.com/csk/items/1940dc29ee5e19ec58b1 compositionapi 2023-05-05 15:27:14
Ruby Rubyタグが付けられた新着投稿 - Qiita Rubyでパフォーマンス計測 https://qiita.com/satreu16/items/5dbc56f929276c4c4fbb bench 2023-05-05 15:14:02
Docker dockerタグが付けられた新着投稿 - Qiita Dcoker composeで遊ぶ https://qiita.com/tyakosuke/items/ef822b0ecec40327287e compose 2023-05-05 15:17:21
技術ブログ Developers.IO EC2からTransfer Familyに名前解決を切り替えてみた https://dev.classmethod.jp/articles/fqdn-from-ec2-to-transfer/ transferfamily 2023-05-05 06:52:42
海外TECH DEV Community 🎉 A Beginner's Guide to useEffect https://dev.to/codexam/a-beginners-guide-to-useeffect-3ej4 A Beginner x s Guide to useEffectWelcome to the world of React Hooks Today we ll dive into one of the most popular hooks useEffect Don t worry we ll make it fun and easy to understand So let s get started What is useEffectuseEffect is a React Hook that allows you to perform side effects in your functional components Side effects are actions that happen outside of your component like fetching data updating the DOM or subscribing to events With useEffect you can manage these side effects without writing a class or function How useEffect worksuseEffect is like a Swiss Army knife for side effects in your functional components It combines the functionality of componentDidMount componentDidUpdate and componentWillUnmount from class components into one simple hook Here s how it works You call useEffect with a function that contains your side effect React runs your side effect function after rendering the component If you provide a cleanup function React will call it when the component is unmounted or when the dependencies change No need to write a class or function Different use casesLet s explore some common use cases for useEffect Fetching data You can use useEffect to fetch data from an API and update your component s state when the data is received Updating the document title Want to change the title of your webpage based on the component s state useEffect to the rescue ‍ ️Setting up event listeners Need to listen for events like window resizing or keyboard input useEffect can help you set up and clean up event listeners Persisting state Want to save your component s state to local storage or a database useEffect can handle that too Timers and intervals If you need to set up a timer or interval in your component useEffect is the perfect tool for the job You can start the timer when the component mounts and clear it when the component unmounts Examples of useEffect use cases Example Fetching dataStrucutreFetchData├ーbutton tsx├ーlocation tsx├ーweather tsx tsximport React useState useEffect from react import fetchWeatherData from weather Import the function to fetch weather datainterface WeatherProps location string const WeatherButtons React FC lt WeatherProps gt location gt const weatherData setWeatherData useState lt any gt null Create state to hold weather data and initialize it to null const requestType setRequestType useState lt string gt Create state to hold the type of request to make and initialize it to an empty string useEffect gt if requestType If a request type has been selected fetchWeatherData location requestType then data any gt Call the function to fetch weather data setWeatherData data Set the weather data to the response from the API requestType location Run the effect when either request type or location changes return lt div className text xl gt lt button className weather current weather button onClick gt setRequestType current When the button is clicked set the request type to current gt Current Weather lt button gt weatherData amp amp If weather data exists lt div className weather json bg gt lt pre className weather button pre wrap gt JSON stringify weatherData null Display the weather data as JSON lt pre gt lt div gt lt div gt export default WeatherButtons This component renders a button that fetches weather data from the API when clicked It has the following features It imports the useState and useEffect hooks from React and the fetchWeatherData function from weather tsx It receives the location prop from its parent component which specifies the city for which weather data should be fetched It defines two state variables using the useState hook weatherData which stores the fetched weather data and requestType which determines what type of weather data to fetch e g current weather day forecast It uses the useEffect hook to fetch weather data from the API when requestType changes i e when the button is clicked and update the weatherData state variable with the fetched data It renders a button with an onClick event that sets the requestType state variable to current i e fetch current weather data If weatherData is not null it renders a pre tag that displays the fetched data in JSON format tsximport React createContext useState from react export const LocationContext createContext lt any gt null Create a context object to hold location dataexport const LocationProvider React FC children gt Create a provider component for the context const location setLocation useState lt string gt New York Create state to hold the current location and initialize it to New York const changeLocation newLocation string gt setLocation newLocation Function to update the location return lt LocationContext Provider value location changeLocation gt children lt LocationContext Provider gt This component creates a context that stores the current location for which weather data should be fetched It has the following features It imports the createContext and useState hooks from React It creates a LocationContext using the createContext hook which is used to pass the location state variable and changeLocation function to child components It defines a LocationProvider component using the useState hook which sets the initial location state variable to New York It defines a changeLocation function that updates the location state variable with a new location It renders the LocationContext Provider component with the location state variable and changeLocation function as its value and its child components as its children tsxconst fetchWeatherData async location string requestType string Promise lt any gt gt const apiKey process env NEXT PUBLIC WEATHER Get the API key from the environment variables const apiUrl location amp appid apiKey Construct the API URL using the location and API key const response await fetch apiUrl Make a request to the API const data await response json Parse the response as JSON return data Return the data export default fetchWeatherData This component defines a function that fetches weather data from the OpenWeatherMap API using the provided location and requestType parameters It has the following features It defines an async function called fetchWeatherData that takes in location and requestType parameters It gets the API key from an environment variable called NEXT PUBLIC WEATHER It constructs the API URL using the location and apiKey variables and uses fetch to make a GET request to the API It uses the json method of the response object to convert the response to a JavaScript object It returns the fetched data as a Promise How to useimport WeatherButtons from components react useEffect FetchData button import LocationProvider from components react useEffect FetchData location lt LocationProvider gt lt WeatherButtons location London units metric theme dark gt lt LocationProvider gt To use these components you can import WeatherButtons and LocationProvider into your own React component and wrap WeatherButtons inside LocationProvider You can then pass in the desired location and optionally units and theme props to WeatherButtons When the button is clicked the weather data for the specified location will be fetched and displayed in JSON format Example UserFetchDataUserFetch├ーData tsx├ーUserFetch tsx tsximport React useEffect useState from react Define the shape of the data object that will be returned by the hooktype Data lt T gt status loading success error data T error Error Custom hook that fetches data from an API endpoint and returns the data objectexport function useFetch lt T gt url string Data lt T gt Create a state variable called data and initialize it with status loading const data setData useState lt Data lt T gt gt status loading useEffect hook that runs when the URL changes useEffect gt Define an asynchronous function called fetchData const fetchData async gt try Fetch data from the API endpoint const response await fetch url const result await response json Update the data state variable with the fetched data setData status success data result catch error Update the data state variable with the error object setData status error error error as Error Call the fetchData function to fetch data from the API endpoint fetchData url Only run the effect when the url changes Return the data object return data The Data type defines the shape of the data object that will be returned by the useFetch hook It contains three properties status data and error The useFetch function takes a URL as its parameter and returns the data object that was defined earlier Within the useFetch function useState is used to create a state variable data and its initial state is set to status loading useEffect is used to fetch the data from the API endpoint It runs only when the URL changes because url is passed as its second argument Inside the useEffect function fetchData is an asynchronous function that uses try and catch blocks to fetch the data from the API endpoint If the fetch is successful the setData function is called with status success data result If there is an error the setData function is called with status error error error as Error Finally useFetch returns the data object tsximport React useState from react import useFetch from Data function UsersFetch Create a state variable called url and initialize it with the API endpoint URL const url setUrl useState Call the useFetch hook with the url state variable const data useFetch lt Array lt id number name string gt gt url Render a button that changes the url state variable when clicked return lt div gt lt button className user fetch button onClick gt setUrl url limit gt Fetch only users lt button gt If the status property of the data object is loading render a loading message data status loading amp amp lt p gt Loading lt p gt If the status property of the data object is success render a list of users data status success amp amp lt ul className user fetch data bg gt data data map user gt lt li key user id gt user name lt li gt lt ul gt If the status property of the data object is error render an error message data status error amp amp lt p gt Error data error message lt p gt lt div gt export default UsersFetch The UsersFetch function is a React component that uses the useFetch hook to fetch data from an API endpoint and render it The component uses useState to create a state variable url with an initial value of The data variable is assigned the result of calling the useFetch hook with url A button is rendered that calls setUrl with a new URL when clicked The component renders different content depending on the status property of the data object If status is loading the component renders a loading message If status is success the component renders a list of users with their names If status is error the component renders an error message with the error object s message Example WidgetWidget├ーColorWidget tsx├ーWidget tsx tsx This function creates a new widget element with the specified background color and adds it to the provided container element export function createWidget color string container HTMLElement Create a new div element to serve as the widget const widget document createElement div Set the widget s background color widget style background color Set the widget s width and height widget style width px widget style height px Set the widget s border radius widget style borderRadius Set the widget s margin widget style margin px Set the widget s border style and color widget style border px solid pink Create a new custom event to be dispatched periodically by the widget const statusChangeEvent new CustomEvent statusChange detail status active Set an interval to dispatch the statusChangeEvent every milliseconds second setInterval gt widget dispatchEvent statusChangeEvent Add the widget to the container element container appendChild widget Return an object with functions to add and remove event listeners as well as to destroy the widget return addEventListener widget addEventListener bind widget removeEventListener widget removeEventListener bind widget destroy gt container removeChild widget Line Define a function called createWidget that takes two arguments color string and container HTMLElement Line Create a new div element with the provided color set its size shape margin and border Line Create a new custom event called statusChangeEvent with a detail property containing status active Line Dispatch the statusChangeEvent every second Line Append the widget to the container Line Return an object that has three properties addEventListener removeEventListener and destroy tsximport React useEffect useRef useState from react import createWidget from Widget interface ColorWidgetProps initialColor string const ColorWidget React FC lt ColorWidgetProps gt initialColor gt useRef hook to create a reference to the container div element const containerRef useRef lt HTMLDivElement gt null useState hook to create a state variable for the color of the widget const color setColor useState initialColor useEffect hook to run side effects when the component mounts or the color state changes useEffect gt Get the current value of the container reference const container containerRef current If the container exists create a widget and add event listeners to it if container Create the widget with the given color and container const widget createWidget color container Define a function to handle the statusChange event of the widget const handleStatusChange event CustomEvent lt status string gt gt console log The status is event detail status Add an event listener to the widget to listen for statusChange events widget as any addEventListener statusChange handleStatusChange Return a cleanup function to remove the widget and event listeners when the component unmounts or the color changes return gt widget destroy widget as any removeEventListener statusChange handleStatusChange color Define a function to update the color state variable with a random hex color const changeColor gt setColor Math floor Math random x toString padStart Render the ColorWidget component with a container div a button to change the color and the color widget itself return lt div className color widget gt lt div className widget container ref containerRef gt lt div gt lt button className widget button onClick changeColor gt Change Color lt button gt lt div gt export default ColorWidget Line Import necessary dependencies and define an interface for ColorWidgetProps Line Define a functional component called ColorWidget that takes initialColor as a prop and returns some JSX Line Create a reference using useRef to store a reference to a div element Line Define a state called color using useState and initialize it with initialColor Line Use useEffect to create a widget using createWidget add an event listener to it and clean up the widget and event listener when the color changes or the component is unmounted Line Define a function called changeColor that generates a random hexadecimal color and sets it as the new color Line Return some JSX that contains a div with a ref to the container reference a button with an onClick event handler that calls changeColor and some CSS classes for styling Example Conditional Effect tsximport React useState useEffect from react export const ConditionalEffect React FC gt state variables for count and message const count setCount useState const message setMessage useState useEffect hook that runs whenever count changes useEffect gt check if count is even or odd if count set message to Even if count is even setMessage Even else set message to Odd if count is odd setMessage Odd count render the component with a button that increments count on click also display the current message and count value return lt div gt lt button className conditional effect button onClick gt setCount count gt Conditional Effect lt button gt lt p className conditional effect text gt message lt p gt lt p className conditional effect text gt Count count lt p gt lt div gt import React useState useEffect from react imports React and the useState and useEffect hooks from the react library const count setCount useState declares a state variable count using the useState hook with an initial value of and a function setCount that allows us to update the count variable const message setMessage useState declares a state variable message using the useState hook with an initial value of an empty string and a function setMessage that allows us to update the message variable useEffect gt count defines an effect that runs whenever the count state variable changes If count is even message is set to Even otherwise it is set to Odd lt button className conditional effect button onClick gt setCount count gt Conditional Effect lt button gt renders a button with a click handler that updates the count state variable when clicked lt p className conditional effect text gt message lt p gt renders the value of message lt p className conditional effect text gt Count count lt p gt renders the value of count Example Timer Effect tsximport React useState useEffect from react export const Timer React FC gt Set the initial state of seconds to using useState hook const seconds setSeconds useState useEffect gt Set an interval to increment seconds state by every ms using setInterval const interval setInterval gt setSeconds seconds gt seconds Clear the interval using clearInterval in the cleanup function return gt clearInterval interval Effect only runs once empty dependency array return lt div gt lt p className timer text gt You have been on this page for seconds seconds lt p gt lt div gt import React useState useEffect from react Import the necessary React components const seconds setSeconds useState Declare a state variable seconds and its corresponding updater function setSeconds initialized to useEffect gt Use the useEffect hook to execute a side effect after the initial render and run cleanup before unmount The dependency array is empty so the effect will only run once after the initial render const interval setInterval gt Set an interval to increment the seconds state by every second setSeconds seconds gt seconds Update the seconds state with the updater function to increment its value by return gt Return a cleanup function to clear the interval when the component is unmounted lt p className timer text gt You have been on this page for seconds seconds lt p gt Render a paragraph element that displays the seconds state variable Example Update Title tsximport React useEffect useState from react export function UpdateTItle const count setCount useState create a state variable count and its update function setCount with an initial value of useEffect gt This is a side effect that runs when the component mounts and whenever count changes It updates the document title with the current count document title You clicked count times count Only run the effect when count changes return lt div gt lt p className update title text gt You clicked count times lt p gt lt button className update title button onClick gt setCount count gt Click me lt button gt lt div gt The code defines a React functional component called UpdateTitle The component initializes a state variable count with an initial value of and its corresponding update function setCount The useEffect hook is used to create a side effect that runs when the component mounts and whenever count changes Inside the effect the document title is updated with the current value of count interpolated into a string The useEffect hook takes an array of dependencies as its second argument When any of the dependencies change the effect will run again In this case the effect only depends on count so it will only run when count changes The component returns a div containing a paragraph element that displays the current value of count and a button that updates count when clicked That s it Now you have a solid understanding of useEffect and how it can help you manage state in your React functional components Happy coding 2023-05-05 06:16:06
ニュース BBC News - Home Local elections 2023: Conservatives suffer early local election losses https://www.bbc.co.uk/news/uk-politics-65485099?at_medium=RSS&at_campaign=KARANGA councils 2023-05-05 06:42:05
ニュース BBC News - Home Suspect arrested after second mass shooting in Serbia https://www.bbc.co.uk/news/world-europe-65490418?at_medium=RSS&at_campaign=KARANGA belgrade 2023-05-05 06:42:06
ニュース BBC News - Home Johanita Dogbey: Man charged with Brixton murder https://www.bbc.co.uk/news/uk-england-london-65491944?at_medium=RSS&at_campaign=KARANGA attacks 2023-05-05 06:41:10
ニュース BBC News - Home Tory council leader ousted by 22-year-old Lib Dem https://www.bbc.co.uk/news/uk-england-berkshire-65487770?at_medium=RSS&at_campaign=KARANGA maidenhead 2023-05-05 06:19:40
IT 週刊アスキー カレーに大量の青ネギ! 松屋の新作は17種のスパイスとねぎが特徴の「ねぎたっぷりスパイスカレー」9日発売 https://weekly.ascii.jp/elem/000/004/135/4135391/ 販売開始 2023-05-05 15:30:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)