Compare commits

..

2 Commits

Author SHA1 Message Date
laktionov-as 12515f925d Сделали таймер 2026-05-28 20:45:57 +03:00
laktionov-as b3662b759f class components 2026-05-28 20:29:26 +03:00
4 changed files with 93 additions and 108 deletions
-27
View File
@@ -8,7 +8,6 @@
"name": "store-client",
"version": "0.0.0",
"dependencies": {
"@tanstack/react-query": "^5.100.14",
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
@@ -1305,32 +1304,6 @@
"win32"
]
},
"node_modules/@tanstack/query-core": {
"version": "5.100.14",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.100.14.tgz",
"integrity": "sha512-5X41dGpxgeaHISCRW2oYwcSycZeULZzAunaudXT9ov1KOTj9xwt0CH6hbwqP1/z74ZWF7rYFnDpyYH07XFcZew==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.100.14",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.100.14.tgz",
"integrity": "sha512-oOr6aRdSFEwWhzxEkD/9ZcItM3+LjBSkeVmadWKwUssAHTsqd/7bOjWrX4AbvEkoEhgAxzN0Xk6H/aYzXiYBAw==",
"license": "MIT",
"dependencies": {
"@tanstack/query-core": "5.100.14"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^18 || ^19"
}
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
+1 -2
View File
@@ -4,13 +4,12 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@tanstack/react-query": "^5.100.14",
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
+92 -77
View File
@@ -1,93 +1,108 @@
import React, {useState, useEffect, useRef } from 'react'
//import { useQuery } from '@tanstack/react-query'
import React from 'react'
function useWindowWidth() {
const [width,setWidth] = useState(window.innerWidth)
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize',handleResize);
return () => window.removeEventListener('resize',handleResize);
},[])
return width
}
function useLocalStorage(key, initValue) {
const [value, setValue] = useState(()=>{
const stored = localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initValue
})
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value))
},[key, value])
return [value,setValue]
}
/*
function useUserData(userId) {
return useQuery(
['user',userId],
() => fetch(`/api/user/${userId}`).then(res => res.json()),
{refetchOnWindowFocus: false}
)
}*/
function useInput(initValue, validate) {
const [value, setValue] = useState(initValue);
const [error, setError] = useState(null);
const onChange = e => {
const newValue = e.target.value
setValue(newValue)
if (validate) {
const validationResult = validate(newValue)
setError(validationResult)
}
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { data: null };
this.handleClick = this.handleClick.bind(this);
}
return { value, error, onChange }
render() {
return (
<div>
{this.state.data ? (
<div>Данные: {this.state.data}</div>
) : (
<div>Загрузка...</div>
)}
<button onClick={this.handleClick}>Обновить</button>
</div>
)
}
componentDidMount() {
fetch('https://api.example.com/data')
.then(responce => responce.json())
.then(json => this.setState({data: json}));
this.timerId = setInterval(()=> console.log('Tick'), 1000);
}
componentWillUnmout() {
clearInterval(this.timerId);
}
handleClick() {
this.setState({data: 'Данные'})
}
}
function useInterval(callback, delay) {
const savedCallback = useRef()
class MyComponent2 extends React.Component {
controller = new AbortController()
componentDidMount() {
fetch('https://api.example.com/data',{ singnal: this.controller.signal })
.then(responce => responce.json())
.then(json => this.setState({data: json}))
.catch(error => {
if(error.name == 'AbortError') {
console.log('Aborted');
} else {
console.log('Other error',error);
}
});
}
componentWillUnmount() {
this.controller.abort()
}
}
class MyComponent3 extends React.Component {
componentDidMount() {
this.loadData();
}
useEffect(()=>{
savedCallback.current = callback
},[callback]);
async loadData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
this.setSate({ data });
} catch {
console.log('error');
}
}
}
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 }
}
useEffect(()=>{
if (delay == null) return
const id = setInterval(()=>{
savedCallback.current()
},delay);
return () => clearInterval(id);
},[delay])
componentDidMount() {
console.log('Timer mounted');
this.interval = setInterval(()=>{
this.setState(prevState => ({seconds: prevState.seconds + 1}))
},1000);
}
componentWillUnmount() {
console.log('Timer unmount');
clearInterval(this.interval);
}
render() {
return <h2>Прошло секунд: {this.state.seconds}</h2>
}
}
function App() {
const width = useWindowWidth();
const [theme, setTheme] = useLocalStorage('theme','light');
const username = useInput(
'',
value => value.length < 3 ? 'минимум 3 символа' : null
)
const [show,setShow] = React.useState(true);
return (
<>
<h1>Hello, React!{width}</h1>
<button onClick={()=>{
setTheme(theme === 'light' ? 'dark' : 'light')
}}>
Сменить тему
</button>
<p><input type="text"
value={username.value}
onChange={username.onChange} />
{ username.error ? username.error : '' }
</p>
<h1>Таймер с классом</h1>
<button onClick={()=>setShow(prev => !prev)}>{show ? 'Скрыть' : 'Показать'} таймер</button>
{show && <Timer />}
</>
)
}
-2
View File
@@ -4,7 +4,5 @@ import { createRoot } from 'react-dom/client'
import App from './App.jsx'
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
)