如何使我的fetchMovieDescription函数在story状态更改后被调用?

huangapple go评论66阅读模式
英文:

How do i make my fetchMovieDescription function to get called after the story state has changed?

问题

I can help you with the translation. Here's the translated code:

import { process } from '../env';
import { Configuration, OpenAIApi } from 'openai';
import { useState, useEffect } from 'react';

const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY
});

const openai = new OpenAIApi(configuration);

export default function StoryPart() {
    const [userInput, setUserInput] = useState("");
    const [story, setStory] = useState("");
    const [images, setImages] = useState("");
    const [storyFetched, setStoryFetched] = useState(false);

    useEffect(() => {
        fetchMovieDescription(story);
    }, [storyFetched]);

    const handleChange = (event) => {
        setUserInput(event.target.value);
    }

    const handleSubmit = async (event) => {
        event.preventDefault();
        await fetchBotReply(userInput);
        setUserInput("");
    }

    async function fetchBotReply(userInput) {
        try {
            const response = await openai.createCompletion({
                model: 'text-davinci-003',
                prompt: `You are an AI developed by OpenAI.
                You have been trained on a vast range of internet text.
                But unlike most AI models, your specialty is in creating unique and compelling movie scenarios.
                You understand the elements of a great movie, including plot development, character arcs, conflict, and resolution.
                You can generate scenarios in any genre, time period, or setting.
                Your task is to write a scenario based on: ${userInput}.You must create the scenario so its easy to split it into 5
                sections.The reason for it is that based on each section i will later ask you to write 5 detailed descriptions
                of an image for later image generation.`,
                max_tokens: 700,
                temperature: 1
            });
            setStory(response.data.choices[0].text);
            setStoryFetched(true);
        } catch (error) {
            console.log(error);
        }
    }

    async function fetchMovieDescription(story) {
        try {
            const response = await openai.createImage({
                prompt: `Create a descriptive and precise prompt for image generation based on this story: ${story}`,
                n: 1,
                size: "512x512",
                response_format: 'url'
            });
            console.log(story);
            setImages(response.data.data[0].url);
            console.log(response.data.data[0].url);
        } catch (error) {
            console.log(error);
        }
    }

    return (
        <div className="StoryPart">
            <form onSubmit={handleSubmit}>
                <label>
                    Story:
                    <input value={userInput} type="text" name="story" placeholder='input prompt' onChange={handleChange}/>
                </label>
                <button type="submit" value="Submit">Submit</button>
            </form>
            {story? <p>{story}</p> : "Writing your story..."}
            {images? <img src={images} alt="movie scene"/> : "Writing your images..."}
        </div>
    )
}

If you have any specific questions or need further assistance, please feel free to ask.

英文:

I cant make the fetchMovieDescription function to get called only after my story state is changed, instead, it gets called in the same time as fetchBotReply and generates a random image instead of the one from the story result.

import { process } from &#39;../env&#39;
import { Configuration, OpenAIApi } from &#39;openai&#39;
import { useState, useEffect } from &#39;react&#39;
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY
})
const openai = new OpenAIApi(configuration)
export default function StoryPart() {
const [userInput, setUserInput] = useState(&quot;&quot;)
const [story, setStory] = useState(&quot;&quot;)
const [images, setImages] = useState(&quot;&quot;)
const [storyFetched, setStoryFetched] = useState(false);
useEffect(() =&gt; {
fetchMovieDescription(story);
}, [storyFetched])
const handleChange = (event) =&gt; {
setUserInput(event.target.value);
}
const handleSubmit = async (event) =&gt; {
event.preventDefault();
await fetchBotReply(userInput);
setUserInput(&quot;&quot;);
}
async function fetchBotReply(userInput) {
try {
const response = await openai.createCompletion({
model: &#39;text-davinci-003&#39;,
prompt: `You are an AI developed by OpenAI.
You have been trained on a vast range of internet text.
But unlike most AI models, your specialty is in creating unique and compelling movie scenarios.
You understand the elements of a great movie, including plot development, character arcs, conflict, and resolution.
You can generate scenarios in any genre, time period, or setting.
Your task is to write a scenario based on: ${userInput}.You must create the scenario so its easy to split it into 5
sections.The reason for it is that based on each section i will later ask you to write 5 detailed descriptions
of an image for later image generation.`,
max_tokens: 700,
temperature: 1
})
setStory(response.data.choices[0].text)
setStoryFetched(true)
} catch (error) {
console.log(error)
}
}
async function fetchMovieDescription(story) {
try {
const response = await openai.createImage({
prompt: `Create a descriptive and precise prompt for image generation based on this story: ${story}`,
n: 1,
size: &quot;512x512&quot;,
response_format: &#39;url&#39;
})
console.log(story)
setImages(response.data.data[0].url)
console.log(response.data.data[0].url)
} catch (error) {
console.log(error)
}
}
return (
&lt;div className=&quot;StoryPart&quot;&gt;
&lt;form onSubmit={handleSubmit}&gt;
&lt;label&gt;
Story:
&lt;input value={userInput} type=&quot;text&quot; name=&quot;story&quot; placeholder=&#39;input prompt&#39; onChange={handleChange}/&gt;
&lt;/label&gt;
&lt;button type=&quot;submit&quot; value=&quot;Submit&quot;&gt;Submit&lt;/button&gt;
&lt;/form&gt;
{story? &lt;p&gt;{story}&lt;/p&gt; : &quot;Writing your story...&quot;}
{images? &lt;img src={images} alt=&quot;movie scene&quot;/&gt; : &quot;Writing your images...&quot;}
&lt;/div&gt;
)
}

i tried making another state storyFetched to change after the story has changed but no effect.

答案1

得分: 1

您的useEffect将在storyFetched状态初始化后(在第一次渲染后)以及每当其值更改时触发。

由于在这种情况下,您不希望在故事被获取之前调用fetchMovieDescription,您可以在useEffect内部添加一个if语句。如果storyFetched为真,这意味着故事已被获取,应调用您的函数。

这是useEffect的重写:

useEffect(() => {
  if (storyFetched) {
    fetchMovieDescription(story);
  }
}, [storyFetched])

这样,只有当storyFetched为真时才调用fetchMovieDescription

英文:

Your useEffect will get fired once the storyFetched state is initialized (after the first render) and every time its value changes.

Since in this case you don't want to call fetchMovieDescription until the story is fetched, you can add an if statement inside the useEffect. If storyFetched is true it means the story is fetched and your function should be called.

This is a rewrite of the useEffect:

useEffect(() =&gt; {
If(storyFetched) {
fetchMovieDescription(story);
}
}, [storyFetched])

This way fetchMovieDescription only when storyFetched is true.

huangapple
  • 本文由 发表于 2023年5月30日 02:50:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359718.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定