How to Build an AI app with React Native in 2024
Fernando Chaves
September 11, 2024



npm install axios @react-native-async-storage/async-storage
{`import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
const API_URL = 'https://api.openai.com/v1/engines/davinci-codex/completions';
export const getAIResponse = async (prompt) => {
try {
const apiKey = await AsyncStorage.getItem('AI_API_KEY');
const response = await axios.post(API_URL, {
prompt: prompt,
max_tokens: 100
}, {
headers: {
'Authorization': \`Bearer \${apiKey}\`,
'Content-Type': 'application/json'
}
});
return response.data.choices[0].text;
} catch (error) {
console.error('Error calling AI API:', error);
return null;
}
};`}
{`import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import { getAIResponse } from './src/aiService';
const AIComponent = () => {
const [input, setInput] = useState('');
const [response, setResponse] = useState('');
const handleSubmit = async () => {
const aiResponse = await getAIResponse(input);
setResponse(aiResponse || 'Failed to get response');
};
return (
<View>
<TextInput
value={input}
onChangeText={setInput}
placeholder="Enter your prompt"
/>
<Button title="Submit" onPress={handleSubmit} />
<Text>{response}</Text>
</View>
);
};
export default AIComponent;`}
{`import AsyncStorage from '@react-native-async-storage/async-storage';
// In your app's initialization code
AsyncStorage.setItem('AI_API_KEY', 'your-api-key-here');`}

