Передача return на уровень выше
Столкнулся с проблемой: с помощью return получается только передать промис в следующий then, а не вернуть его из функции. Как можно решить эту проблему?
Код приложил ниже
const App = () => {
fetch('http://localhost:3001/getprops')
.then(res => res.json())
.then(res => {
// Отсюда вернуть значение из функции App, а не передать его в следующую цепочку then
})
};
update: Исправил, вышло это:
const App = () => {
const [error, setError] = useState(undefined)
const [smth, setSmth] = useState(undefined)
useEffect(() => {
fetch('http://localhost:3001/getprops')
.then(res => res.json())
.then(setSmth)
.catch(setError)
}, [])
return (
error ? <h3>Ошибка</h3>
: !smth ? <div></div>
: <div className="App" id="App">
// мое приложение
</div>
)
};
Ответы (2 шт):
Автор решения: SwaD
→ Ссылка
Как то так должно выглядеть
const App = () => {
const [jsxEl, setJsx] = useState(null);
const dataRequest = () => {
fetch('http://localhost:3001/getprops')
.then(res => res.json())
.then(res => {
// Придумываем jsx
setJsx(<div>{res.text}</div>)
})
}
useEffect(() => {
dataRequest();
}, []);
return (
<>
{jsxEl}
</>
)
}
В таком случае, можно будет повторно, при необходимости вызывать функцию запроса данных
Автор решения: Qwertiy
→ Ссылка
function App() {
const [error, setError] = useState()
const [smth, setSmth] = useState()
useEffect(() => {
fetch('/smth')
.then(resp => resp.json())
.then(res => setSmth(res))
.catch(err => setError(err))
}, [])
return (
error ? <h1>Ooops...</h1>
: !smth ? <h1>Loading...</h1>
: <SomeOtherThing smth={smth} />
)
}